class Node { int val; Node next; Node(int val) { this.val = val; this.next = null; } } public class Main { public static Node reverseList(Node head) { Node prev = null; Node curr = head; while (curr != null) { Node nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } return prev; } public static void printList(Node head) { Node curr = head; while (curr != null) { System.out.print(curr.val + " -> "); curr = curr.next; } System.out.print("null"); } public static void main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); Node reversed = reverseList(head); printList(reversed); } }
The iterative reversal changes the direction of the next pointers one by one. Starting from 1 -> 2 -> 3 -> null, after reversal it becomes 3 -> 2 -> 1 -> null.
class Node { int val; Node next; Node(int val) { this.val = val; this.next = null; } } public class Main { public static Node reverseList(Node head) { Node prev = null; Node curr = head; while (curr != null) { Node nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } return prev; } public static void printList(Node head) { Node curr = head; while (curr != null) { System.out.print(curr.val + " -> "); curr = curr.next; } System.out.print("null"); } public static void main(String[] args) { Node head = null; Node reversed = reverseList(head); printList(reversed); } }
If the input head is null, the reverse function returns null immediately. Printing null means no nodes are printed, just 'null'.
public static Node reverseList(Node head) {
Node prev = null;
Node curr = head;
while (curr.next != null) {
Node nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}The loop condition 'curr.next != null' stops before processing the last node. So the last node is never reversed or linked properly, resulting in an incomplete reversed list.
class Node { int val; Node next; Node(int val) { this.val = val; this.next = null; } } public class Main { public static Node reverseList(Node head) { Node prev = null; Node curr = head; while (curr != null) { Node nextTemp = curr.next; curr.next = prev; prev = curr; curr = nextTemp; } return prev; } public static void printList(Node head) { Node curr = head; while (curr != null) { System.out.print(curr.val + " -> "); curr = curr.next; } System.out.print("null"); } public static void main(String[] args) { Node head = new Node(10); head.next = new Node(20); head.next.next = new Node(30); head.next.next.next = new Node(40); head.next.next.next.next = new Node(50); Node reversed = reverseList(head); printList(reversed); } }
The iterative reversal reverses all next pointers, so the list 10 -> 20 -> 30 -> 40 -> 50 becomes 50 -> 40 -> 30 -> 20 -> 10 -> null.
When reversing, changing curr.next breaks the link to the rest of the list. nextTemp saves the next node before changing the link, so we don't lose access. prev keeps track of the reversed part.
