Reverse a singly linked list.

Iterative

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode newHead = null;

while (head != null){
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}

return newHead;
}
}

Recursive

1
2
3
4
5
6
7
8
9
10
11
public ListNode reverseList(ListNode head) {
return reverseListInt(head, null);
}

public ListNode reverseListInt(ListNode head, ListNode newHead) {
if(head == null)
return newHead;
ListNode next = head.next;
head.next = newHead;
return reverseListInt(next, head);
}