Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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