單向鍊錶的倒置

2021-10-21 10:14:37 字數 634 閱讀 6246

首先要判斷當鍊表的長度為0或者1的時候,直接返回當前節點即可,否則需要兩個輔助「指標」pre、next,分別指向頭結點的前結點和後結點,不然next屬性改變的時候就會丟失原先列表的結點位址。

首先讓pre = null, next = null;迴圈當head != null 的時候,讓next = head.next,head.next = pre,pre = head,head = next。

最終當head=null的時候,迴圈結束,此時的pre指向原先的尾結點,即鍊錶倒置後的頭結點,函式返回pre即可。

/*

public class listnode

}*/public class solution

listnode pre = null;

listnode next = null;

while (head != null)

return pre;}}

鍊錶的倒置

public static void reorder ref node listhead node lefthead listhead node righthead null node current lefthead.next lefthead.next null while current nu...

鍊錶 反轉單向鍊錶

思路 從第二個元素開始。1 刪除當前元素。2 把當前元素放到頭結點位置。其中需要宣告3個變數 headnode 頭結點 prenode 前乙個結點 currentnode 當前結點 具體步驟如圖所示 實現 反轉單鏈表方法實現類 created by liujinjin on 17 1 19.publ...

鍊錶1 單向鍊錶

鍊錶中最簡單的一種是單向鍊錶,它包含兩個域,乙個資料域和乙個指標域,指標域指向鍊錶中的下乙個節點,最後乙個節點的指標域指向乙個空值 鍊錶最基本的結構是在每個節點儲存資料和到下乙個節點的位址,在最後乙個節點儲存乙個特殊的結束標記,另外在乙個固定的位置儲存指向第乙個節點的指標,有的時候也會同時儲存指向最...