Reverse a singly linked list.
Hint:
Recursive solution:
Update on 11/6/15:
Recursive solution using two pointers:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Iterative solution:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseList(ListNode head) { if (head == null || head.next == null ) { return head; } ListNode prev = null ; ListNode curr = head; ListNode next = head.next; while (curr != null ) { curr.next = prev; prev = curr; curr = next; if (next != null ) { next = next.next; } } return prev; } } |
Recursive solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseList(ListNode head) { if (head == null || head.next == null ) { return head; } ListNode next = head.next; ListNode newHead = reverseList(next); next.next = head; head.next = null ; return newHead; } } |
Update on 11/6/15:
Recursive solution using two pointers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseList(ListNode head) { if (head == null || head.next == null ) { return head; } return reverseListHelper( null , head); } private ListNode reverseListHelper(ListNode prev, ListNode curr) { if (curr == null ) { return prev; } ListNode newHead = reverseListHelper(curr, curr.next); curr.next = prev; return newHead; } } |
Though this is straightforward, I get confused with the extra pointer names, I found a easier way of naming things with code from here. Reverse a Single Linkedlist Java
ReplyDelete