單鏈表反轉
先上代碼:
//反轉單鏈表
public static void reversetList(LinkNode head) {
if(head.next == null || head.next.next == null) {
return ;
}
//定義一個輔助的變量幫助我們遍歷原來的鏈表
LinkNode index = head.next;
LinkNode temp = null;
LinkNode newHead = new LinkNode(0);
while (index != null) {
//先暫時保存當前節點的下一個節點,因爲後面需要使用
temp = index.next;//1
//將index的下一個節點指向新的鏈表的最前端
index.next = newHead.next;//2
//newHead.next = index.next;
//將index 連接到新的鏈表上
newHead.next = index;//3
//index後移
index = temp; //4
}
head.next = newHead.next;
}
思路:
一.先定義一個輔助變量index幫我遍歷整個列表;
在定義一個臨時節點用來存儲當前節點的下一個節點
最後定義一個新表頭
二.第一次循環
1.先保存index的下一個節點,讓index指向新表頭指向的下一個節點(第一次循環時指向爲null)
2.則是讓新表頭的指針指向index節點。
3.讓index後移(變成當時保存的temp節點) 進行下一次的循環。第一次循環結束
三.第二次循環也差不多這裏
後面的步驟都是如此,大家可以自己想想