Given the
head
of a singly linked list, reverse the list, and return the reversed list.
(給定串列鏈結,將其翻轉並將其回傳)
Image Not Showing Possible ReasonsLearn More →
- The image was uploaded to a note which you don't have access to
- The note which the image was originally uploaded to has been deleted
題目要求需要翻轉整個串列鏈結,首先需要了解翻轉一個節點所需要的資訊是
curr
prev
next
prev = NULL
,用於指向個節點,而對於開頭節點來說上個節點為空所以初始化為NULLcurr
,用於指向當前節點curr
為空
temp
,將下個節點記錄起來curr->next = prev
prev = curr
curr = temp
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* prev = NULL;
struct ListNode* curr = head;
while(curr) {
struct ListNode* temp = curr->next;
curr->next = prev;
prev = curr;
curr = temp;
}
return prev;
}