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:/** * 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:
/** * 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:
/** * 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