0%

LeetCode LinkedList

Reverse a LinkedList

Iterative

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static ListNode reverse(ListNode head) {
if (head == null) {
return head;
}
ListNode prev = null;
ListNode curr = head;
ListNode next = head.next;
while (next != null) {
ListNode nextNext = next.next;
curr.next = prev;
next.next = curr;
prev = curr;
curr = next;
next = nextNext;
}
return curr;
}

Recursive

1
2
3
4
5
6
7
8
9
10
11
12
public static ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}

ListNode lastEnd = head.next;
ListNode lastStart = reverseList(head.next);
lastEnd.next = head;
head.next = null;

return lastStart;
}