leetcode 反轉鍊錶(幾種不同的解法)

2021-10-08 19:01:42 字數 1065 閱讀 7350

用三個指標分別指向前三個節點,然後依次往後挪

/**

* definition for singly-linked list.

* struct listnode

* };

*/class

solution

//如果鍊錶無元素或只有乙個頭結點,則直接返回頭結點即可

listnode *p1=head;

listnode *p2=head-

>next;

listnode *p3=head-

>next-

>next;

p1->next=

nullptr

;//第乙個頭結點反轉之後變成尾部,則next指向空

while

(p3!=

nullptr

)//注意,當最後一次的時候p3節點是null,則不在進行迴圈,所以要手動去反轉一次

p2->next=p1;

return p2;}}

;

/**

* definition for singly-linked list.

* struct listnode

* };

*/class

solution

return prenode;}}

;

leetcode上的解釋 非常經典

—————————————————————————————————

public

class

solution

listnode newhead =

reverselist

(head.next)

; head.next.next = head;

head.next = null;

return newhead;

}}

LeetCode 反轉鍊錶

反轉乙個單鏈表。示例 輸入 1 2 3 4 5 null 輸出 5 4 3 2 1 null高階 你可以迭代或遞迴地反轉鍊錶。你能否用兩種方法解決這道題?思路 雙指標,先用乙個指標算出鍊錶結點個數n,每次快指標從頭往先前移動n 步,慢指標往前移動1步進行交換即可。definition for sin...

LeetCode 反轉鍊錶

反轉乙個單鏈表。示例 輸入 1 2 3 4 5 null 輸出 5 4 3 2 1 null 思路分析 直接一趟掃瞄即可。方法二 遞迴 definition for singly linked list.struct listnode class solution listnode reversea...

反轉鍊錶 LeetCode

遞迴版本稍微複雜一些,其關鍵在於反向工作。假設列表的其餘部分已經被反轉,現在我該如何反轉它前面的部分?假設列表為 n1 nk 1 nk nk 1 nm 若從節點 nk 1 到 nm 已經被反轉,而我們正處於 nk n1 nk 1 nk nk 1 nm 我們希望 nk 1 的下乙個節點指向 nk 所以...