遞迴控制 鍊錶反轉

2022-09-17 13:54:24 字數 1597 閱讀 7356

1.反轉思路

2.j**a**實現

鍊錶反轉的意思是將1→2→3→4→5→null反轉為5→4→3→2→1→null

反轉鍊錶的遞迴思路如下:

假設2345這一段鍊錶能夠反轉成功,則只需將1→2345的指標改為2345→1,然後1→null即可

以此類推,即可求得反轉鍊錶

2.1 結點和建立鍊錶的實現

結點和建立鍊錶的實現同上文 遞迴控制-建立鍊錶

2.2 鍊錶反轉的實現

依據反轉思路實現遞迴**即可,再處理size == 0size == 1的特殊情況。

/**

* reverses a linked list.

** @param head the linked list to reverse

* @return head of the reversed linked list

*/public node reverselinkedlist(node head)

// size == 1

if (head.getnext() == null)

node newhead = reverselinkedlist(head.getnext());

head.getnext().setnext(head);

head.setnext(null);

return newhead;

}

優化一下:

public node reverselinkedlist(node head) 

node newhead = reverselinkedlist(head.getnext());

head.getnext().setnext(head);

head.setnext(null);

return newhead;

}

2.3 測試用例

測試程式是否正確執行:

public static void main(string args)
執行結果為

main所在j**a檔案全部**:

import j**a.util.arraylist;

import j**a.util.arrays;

public class linkedlistreverser

node newhead = reverselinkedlist(head.getnext());

head.getnext().setnext(head);

head.setnext(null);

return newhead;

}public static void main(string args)

}

遞迴(鍊錶反轉)

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

反轉鍊錶(非遞迴,哨兵,遞迴)

給你單鏈表的頭節點 head 和兩個整數 left 和 right 其中 left right 請你反轉從位置 left 到位置 right 的鍊錶節點,返回 反轉後的鍊錶 非遞迴解法 反轉cur.next cur.next pre pre cur cur next next cur.next 新建...

遞迴實現鍊錶的反轉

我對遞迴的理解一直不是非常透徹,這裡想要用遞迴實現鍊錶的反轉,寫的時候發現自己連鍊錶的定義都忘記了 還是 寫得太少了 include stdio.h include include iostream using namespace std struct node node creat int a r...