[LeetCode] #206. Reverse Linked List
Mar 15, 2021
[Easy][Question]: Given the head
of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
- The number of nodes in the list is the range
[0, 5000]
. -5000 <= Node.val <= 5000
My Solution[C++]:
[Ideas]: 用1->2->3->4->5舉例,用疊代的方式,最後一層為head=4,head->next=5,代入後return5,從最尾巴的地方5變成新的node的頭,再把head -> next -> next = head,意思是4->5->next=4,所以5->4,下一行head -> next = NULL;,4->NULL,以此類推。