public class ReverseLinkedList {
public static void main(String[] args) {
//遞歸版本
Node node = reverse(firstNode);
for(;node != null;){
System.out.println(node.data);
node = node.next;
}
//非遞歸版本
Node node2 = reverseForeach(firstNode);
for(;node2 != null;){
System.out.println(node2.data);
node2 = node2.next;
}
}
private static class Node{
//數(shù)據(jù)
Integer data;
//next指針
Node next;
}
private static final Node firstNode;
static {
firstNode = new Node();
firstNode.data = 1;
Node linkNode2 = new Node();
linkNode2.data = 2;
Node linkNode3 = new Node();
linkNode3.data = 3;
Node linkNode4 = new Node();
linkNode4.data = 4;
Node linkNode5 = new Node();
linkNode5.data = 5;
Node linkNode6 = new Node();
linkNode6.data = 6;
firstNode.next = linkNode2;
linkNode2.next = linkNode3;
linkNode3.next = linkNode4;
linkNode4.next = linkNode5;
linkNode5.next = linkNode6;
}
//遞歸版本
public static Node reverse(Node node){
if(node == null || node.next == null){
return node;
}else{
Node head = reverse(node.next);
node.next.next = node;
node.next = null;
return head;
}
}
//非遞歸版本
public static Node reverseForeach(Node node){
//初始化;
Node previousNode = null;
Node currentNode = node;
Node headNode = node;
while(currentNode != null){
Node nextNode = currentNode.next;
if(nextNode == null){
headNode = currentNode;
}
//這里的pre current是對于下一次遍歷來說
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
return headNode;
}
}
單鏈表反轉(zhuǎn)(遞歸與非遞歸實(shí)現(xiàn))
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門搂橙,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人笛坦,你說我怎么就攤上這事区转。” “怎么了版扩?”我有些...
- 文/不壞的土叔 我叫張陵废离,是天一觀的道長。 經(jīng)常有香客問我资厉,道長厅缺,這世上最難降的妖魔是什么蔬顾? 我笑而不...
- 正文 為了忘掉前任宴偿,我火速辦了婚禮,結(jié)果婚禮上诀豁,老公的妹妹穿的比我還像新娘窄刘。我一直安慰自己,他們只是感情好舷胜,可當(dāng)我...
- 文/花漫 我一把揭開白布娩践。 她就那樣靜靜地躺著,像睡著了一般烹骨。 火紅的嫁衣襯著肌膚如雪翻伺。 梳的紋絲不亂的頭發(fā)上,一...
- 文/蒼蘭香墨 我猛地睜開眼急灭,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了谷遂?” 一聲冷哼從身側(cè)響起葬馋,我...
- 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后畴嘶,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體扫尖,經(jīng)...
- 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
- 正文 我和宋清朗相戀三年掠廓,在試婚紗的時候發(fā)現(xiàn)自己被綠了换怖。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
- 正文 年R本政府宣布,位于F島的核電站切端,受9級特大地震影響彻坛,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜踏枣,卻給世界環(huán)境...
- 文/蒙蒙 一昌屉、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧茵瀑,春花似錦间驮、人聲如沸。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至鸿捧,卻和暖如春屹篓,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背匙奴。 一陣腳步聲響...
- 正文 我出身青樓恳邀,卻偏偏與公主長得像,于是被迫代替她去往敵國和親灶轰。 傳聞我的和親對象是個殘疾皇子谣沸,可洞房花燭夜當(dāng)晚...