LeetCode Algorithm 206. 反转链表
生活随笔
收集整理的這篇文章主要介紹了
LeetCode Algorithm 206. 反转链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
206. 反轉鏈表
Ideas
關于鏈表的題目其實畫個圖就很清晰了。
可以想象成兩個部分,左邊是已經完成翻轉的鏈表,以pre為頭結點,右邊是還未翻轉的鏈表,以cur為頭結點,每次獲取cur的下一個結點item,然后將cur的next指向pre,再將cur設置為item,繼續處理下一個結點。
Code
C++
class Solution { public:ListNode* reverseList(ListNode* head) {ListNode* cur = head;ListNode* pre = nullptr;while (cur) {ListNode* item = cur->next;cur->next = pre;pre = cur;cur = item;}return pre;} };Python
class Solution:def reverseList(self, head: ListNode) -> ListNode:new_head = Nonewhile head:help_node = head.nexthead.next = new_headnew_head = headhead = help_nodereturn new_head總結
以上是生活随笔為你收集整理的LeetCode Algorithm 206. 反转链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PAT (Basic Level) Pr
- 下一篇: LeetCode 92. Reverse