Skip to content

Instantly share code, notes, and snippets.

@forkercat
Created October 19, 2019 08:48
Show Gist options
  • Save forkercat/9d70781010b39a33b5b6cb23f2dc753b to your computer and use it in GitHub Desktop.
Save forkercat/9d70781010b39a33b5b6cb23f2dc753b to your computer and use it in GitHub Desktop.
ReverseLinkedList
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
// recursion
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// head p1 p2 p3
// head p3 p2 p1->null
// p3 p2 p1 head
ListNode reversed = reverseList(head.next);
ListNode tail = head.next;
tail.next = head;
head.next = null;
return reversed;
}
// iteration
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
// null a b c
// prev p temp
// prev p
// prev p
// prev p
ListNode prev = null;
ListNode p = head;
while (p != null) {
ListNode temp = p.next;
p.next = prev;
// update
prev = p;
p = temp;
}
return prev;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment