Reverse a linked List (iterative and recursive way)
// iterative
public ListNode reverse(ListNode head) {
if(head == null) {
return head;
}
ListNode prev = null;
while(head != null) {
ListNode nextNode = head.next;
head.next = prev;
prev = head;
head = nextNode;
}
return prev;
}
// recursive
public ListNode reverse2(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode nextNode = head.next;
ListNode newHead = reverse2(nextNode);
nextNode.next = head;
head.next = null;
return newHead;
}