反轉單鏈表:輸入煉表頭節點,輸入反轉後的煉表頭節點第一次想到的解法(時間和空間複雜度較高)
將單鏈表每個節點依次讀入到棧中,然後出棧,重新連線成反轉後的單鏈表
public static listnode convert(listnode node)
stack
stack
=new
stack
<>();
//入棧
while (node !=
null)
listnode header
=stack
.pop();
listnode current =
header;
listnode next;
while (!
stack
.isempty())
return
header;
}
快速解法,通過更改鍊錶節點的指標(引用)來直接反轉
public
static listnode fastconvert(listnode node)
//前乙個節點
listnode pre = null;
//當前節點
listnode current = node;
//下乙個節點
listnode next;
//新的頭節點
listnode header = null;
while (current != null)
//當前節點前節點變成後節點
current.next = pre;
//前乙個節點後移
pre = current;
//當前節點後移
current = next;
}return header;
}
單鏈表反轉 java版
head a b c 變成 head c b a 我們可以用迴圈的方式去實現,遍歷一次鍊錶即可。1.用乙個臨時變數tmp儲存 a的下乙個元素b,a的next指向null,即 由頭變尾 head指向null。head null a b c tmp b 2.因為此時tmp就是b,所以將tmp指向tmp的...
Java單鏈表的反轉
前段時間有同事面試,給面試的人都提乙個演算法問題那就是單鏈表的反轉,好多小夥伴都不會,或者表示一聽演算法就懵逼了,自己寫了乙個。就是5 4 6 8 9 1 2 7,反轉輸出7 2 1 9 8 6 4 5,我自己寫的反轉有兩種方式。一種是遞迴,一種是遍歷,也是很普通的兩種方式。一 遞迴的方式 先看圖 ...
單鏈表反轉
單鏈表反轉,可以用迴圈做,當然也可以遞迴 詳見 include includestruct node 3 1 4 6 2 1 1 3 4 6 2 2 4 1 3 6 2 3 6 4 1 3 2 4 2 6 4 1 3 5 迴圈反轉,即依次改動3個指標值,直到鍊錶反轉完成 比如,上面第 1 行到第 2...