In linked list using variables like prev, curt, next are more meaningful.
//iterative way
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode prev = null;
ListNode curt = head;
// 1 -> 2 ->3
// prev curt
// 1 <- 2 3
// prev curt
while (curt != null) {
ListNode temp = curt.next;
curt.next = prev;
prev = curt;
curt = temp;
}
return prev;
}
}
//recursion way
public class Solution {
public ListNode reverseList(ListNode head) {
/* recursive solution */
return reverseListInt(head, null);
}
private ListNode reverseListInt(ListNode curt, ListNode prev) {
if (curt == null)
return prev;
ListNode next = curt.next;
curt.next = prev;
return reverseListInt(next, curt);
}
}