Skip to content

Instantly share code, notes, and snippets.

@cangoal
Last active March 16, 2016 13:43
Show Gist options
  • Save cangoal/01aca3c934fe7cafbadf to your computer and use it in GitHub Desktop.
Save cangoal/01aca3c934fe7cafbadf to your computer and use it in GitHub Desktop.
LeetCode - Reverse Linked List
//
public ListNode newhead = null;
public ListNode reverseList(ListNode head) {
if(head == null) return head;
helper(head, head.next);
return newhead;
}
public void helper(ListNode pre, ListNode cur){
if(cur == null){
newhead = pre;
return;
}
helper(cur, cur.next);
cur.next = pre;
pre.next = null;
}
// recursive solution
public ListNode newhead = null;
public ListNode reverseList(ListNode head) {
if(head == null) return head;
helper(head);
return newhead;
}
public ListNode helper(ListNode pre){
if(pre.next == null){
newhead = pre;
return pre;
}
ListNode cur = helper(pre.next);
cur.next = pre;
pre.next = null;
return pre;
}
// iterative soltuion
public ListNode reverseList(ListNode head) {
if(head == null) return head;
ListNode dummyNode = new ListNode(0);
ListNode pre = dummyNode;
while(head != null){
ListNode next = head.next;
head.next = pre.next;
pre.next = head;
head = next;
}
return dummyNode.next;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment