劍指 Offer 24. 反轉鏈表
題目鏈接

方法一:翻轉當前節點的后一個節點指向,讓其指向頭部,
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = new ListNode();
pre->next = head;
ListNode* cur = head;
while(cur != nullptr && cur->next != nullptr)
{
ListNode* p = cur->next;
cur->next = cur->next->next;
p->next = pre->next;
pre->next = p;
}
return pre->next;
}
};
方法二:翻轉當前節點的指向,回傳最后一個值作為答案
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
ListNode* ans = nullptr;
while(cur != nullptr)
{
ListNode* p = cur->next;
cur->next = pre;
ans = cur; // 保存最后一個值,便于回傳答案
pre = cur;
cur = p;
}
return ans;
}
};
兩種方法類似,如果有其他更好的方法,歡迎評論!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/226972.html
標籤:其他
上一篇:自動白平衡--灰度世界演算法(Gray World Algorithm)
下一篇:C語言用三目運算實作判斷大寫
