Iterative approach.
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode newHead = null;
while (head != null) {
ListNode next = head.next; // Save the next link
head.next = newHead; // Disconnect the current next link and link it to the new one
newHead = head; // Move to the next node
head = next;
}
return newHead;
}
}
Recursive approach.
public class Solution {
public ListNode reverseList(ListNode head) {
return helper(head, null);
}
public ListNode helper(ListNode head, ListNode newHead) {
if (head == null)
return newHead;
ListNode next = head.next;
head.next = newHead;
return helper(next, head);
}
}