Skip to content

Instantly share code, notes, and snippets.

@dryear
Created October 15, 2016 21:55
Show Gist options
  • Save dryear/0e475d1947f45e75735ae8d8082a466d to your computer and use it in GitHub Desktop.
Save dryear/0e475d1947f45e75735ae8d8082a466d to your computer and use it in GitHub Desktop.
LeetCode 206. Reverse Linked List
/**
* 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
}
}
@ShifasCollections
Copy link

great

@MOMA7777
Copy link

nice !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment