206. Reverse Linked List
Question:
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Input: head = [1,2]
Output: [2,1]
Input: head = []
Output: []
Source code
Version 1
Idea:
A demonstration is shonw as below:
There are four steps to do: 1) Declare a curr
variable that it's a pointer of ListNode to point head ListNode. Shift one position every loop. 2) Change a head->next
to prev
ListNode. It means proceeding the redirection or revering. Notice: prev
ListNode is a new ListNOde with no value (only NULL). 3) Update prev
to head
. 4) Update head
to curr
. Repeat (1) - (4) steps until head
is NULL.
1 | /** |