206. Reverse Linked List
Reverse a singly linked list, return the head of the reversed linked list.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode oldNext = curr.next; // 1. stores the old next
curr.next = prev; // 2. the current points to the previous
prev = curr; // 3. the current becomes a new previous
curr = oldNext; // 4. the current moves on
}
return prev;
}
}