演算法 單鏈表反轉(LeetCode 206)

2021-10-23 20:54:39 字數 1506 閱讀 2588

不多說廢話,題目是這樣子的

反轉乙個單鏈表。

示例:輸入: 1->2->3->4->5->null

輸出: 5->4->3->2->1->null

高階:你可以迭代或遞迴地反轉鍊錶。你能否用兩種方法解決這道題?

單鏈表反轉,大家說有很多種辦法,其實無非就是頭插法的各種實現!

1、通過迴圈

2、通過遞迴

1、建立乙個虛擬節點和建立乙個臨時指標temp

2、將temp指向head(鍊錶的表頭)

將head指標往後移動(head=head.next)

然後temp.next = 虛擬節點.next

接著 虛擬head.next=temp

3、以此類推

4、如圖,最後返回虛擬指標就可以

其實**的關鍵就是while迴圈中,那幾步的順序不能亂!

class solution 

//虛擬頭結點

listnode rehead = new listnode(0);

//建立臨時指標

listnode temp = null;

while(head != null)

//最後返回臨時指標,就是最後乙個節點

return temp;}}

沒有**,大家看看**吧

關鍵的難點在於,你的return必須是最後乙個節點!!

public listnode reverselist(listnode head) 

listnode temp = reverselist(head.next);

//如果鍊錶是 1->2->3->4->5,那麼此時的temp就是5

//而head是4,head的下乙個是5,下下乙個是空

//所以head.next.next 就是5->4

head.next.next = head;

//防止鍊錶迴圈,需要將head.next設定為空

head.next = null;

//每層遞迴函式都返回temp,也就是最後乙個節點

return temp;

}

單鏈表反轉演算法

struct listnode 想到兩種方法 想法是構建乙個新的單鏈表,然後遍歷原來的單鏈表,每遍乙個就把它插入到最新的單鏈表的開頭,下面是 struct listnode reverselist struct listnode list temp list last null while temp...

C 演算法 反轉單鏈表

反轉單鏈表,我使用了兩種方法,不過他們都很相近。宣告 class clist 宣告反轉單鏈表函式 void reversesll clist clist prenode nullptr void csinglelinkedlist reversesll clist node,clist prenod...

演算法題 反轉單鏈表

時間限制 1秒 空間限制 32768k 輸入乙個鍊錶,反轉鍊錶後,輸出鍊錶的所有元素。解法一.迴圈反轉鍊錶 非遞迴法 整體思路就是,從原鍊錶的頭部乙個乙個取節點並插入到新鍊錶的頭部 p始終指向要反轉的結點 newhead 指向反轉後的首結點 每反轉乙個結點,把p結點的next指向newhead,ne...