Created
October 15, 2016 21:55
-
-
Save dryear/0e475d1947f45e75735ae8d8082a466d to your computer and use it in GitHub Desktop.
LeetCode 206. 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
/** | |
* https://leetcode.com/problems/reverse-linked-list/ | |
* | |
* O(n) runtime, O(1) space | |
* | |
* this question can be solved by using an iteration method or a recursion method | |
*/ | |
/** | |
* Definition for singly-linked list. | |
* public class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { val = x; } | |
* } | |
*/ | |
// iteration | |
public class Solution { | |
public ListNode reverseList(ListNode head) { | |
if (head == null || head.next == null) { | |
return head; | |
} | |
ListNode cur = head; | |
head = null; | |
while (cur != null) { | |
ListNode next = cur.next; | |
cur.next = head; | |
head = cur; | |
cur = next; | |
} | |
return head; | |
} | |
} | |
// recursion | |
public class Solution { | |
public ListNode reverseList(ListNode head) { | |
if (head == null || head.next == null) { | |
return head; | |
} | |
ListNode next = head.next; | |
ListNode newHead = reverseList(next); // recursively reverse the sub list with nodes after the current node and return ites head | |
next.next = head; // next must be the last node in the reversed sub list | |
// add the current node after the reversed sub list | |
head.next = null; // cut off the link between the current node and nodes after it | |
return newHead; // return the new head | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
great