leetcode 反轉鍊錶(遞迴實現含講解)

2021-09-22 02:54:05 字數 728 閱讀 5421

public class listnode 

public int getdata()

public void setdata(int data)

public listnode getnext()

public void setnext(listnode next)

public static void main(string args) 

// 呼叫反轉方法

head = reverse1(head);

system.out.println("\n**************************");

// 列印反轉後的結果

while (null != head)

}/**

* 遞迴,在反轉當前節點之前先反轉後續節點

*/public static listnode reverse1(listnode head)

listnode rehead = reverse1(head.getnext());// 先反轉後續節點head.getnext()

head.getnext().setnext(head);// 將當前結點的指標域指向前一結點

head.setnext(null);// 前一結點的指標域令為null;

return rehead;// 反轉後新鍊錶的頭結點

}

遞迴(鍊錶反轉)

將乙個單鏈表反轉,結果得到的是鍊錶的最後乙個,以及第乙個。確實是反轉了,但是只剩下兩個元素了。public static node reversenode node node node newheadnode reversenode node.getnext node.setnext null ne...

LeetCode 反轉鍊錶

反轉乙個單鏈表。示例 輸入 1 2 3 4 5 null 輸出 5 4 3 2 1 null高階 你可以迭代或遞迴地反轉鍊錶。你能否用兩種方法解決這道題?思路 雙指標,先用乙個指標算出鍊錶結點個數n,每次快指標從頭往先前移動n 步,慢指標往前移動1步進行交換即可。definition for sin...

LeetCode 反轉鍊錶

反轉乙個單鏈表。示例 輸入 1 2 3 4 5 null 輸出 5 4 3 2 1 null 思路分析 直接一趟掃瞄即可。方法二 遞迴 definition for singly linked list.struct listnode class solution listnode reversea...