Last active
March 16, 2016 13:43
-
-
Save cangoal/01aca3c934fe7cafbadf to your computer and use it in GitHub Desktop.
LeetCode - Reverse Linked List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| 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