Swift 實現鍊錶反轉

2021-10-11 02:46:29 字數 1344 閱讀 1451

//示例:

//輸入: 1->2->3->4->5->null

//輸出: 5->4->3->2->1->null

//高階:

//你可以迭代或遞迴地反轉鍊錶。你能否用兩種方法解決這道題?

class listnode 

}class solution else

}//初始化

func initnode() -> listnode

return head ?? listnode(0)

}//求鍊錶長度

func getlenght(_ head: listnode?) -> int

var lenght = 0

current = head

while current != nil

return lenght

}//迭代法實現鍊錶反轉

func reverselist(_ head: listnode?) -> listnode?

return cur

}//遞迴法實現鍊錶反轉

func reverselist2(_ head: listnode?) -> listnode?

let newnode = reverselist2(head?.next)

head?.next?.next = head

head?.next = nil

return newnode

}//列印鍊錶

func println(_ node: listnode?)

current = node

while current != nil

}}

//應用呼叫

let solution = solution()

let node = solution.initnode()

print("--------反轉前-------")

solution.println(node)

let newnode1 = solution.reverselist(node)

print("--------反轉後-------")

solution.println(newnode1)

let newnode = solution.reverselist2(newnode1)

print("--------再次反轉後-------")

solution.println(newnode)

print("鍊錶長度:", solution.getlenght(newnode))

java實現鍊錶反轉

完整 及詳細的注釋如下 package com.dhasa.test company dhasa author dl public class linkedlistdemo class linkedlist public void sethead node head 內部類node author d...

反轉鍊錶(Java實現)

題目描述 輸入乙個鍊錶,反轉鍊錶後,輸出新鍊錶的表頭。解題思路 當對乙個節點的next指標進行反轉時,會造成鍊錶的斷裂,需要儲存當前節點的next節點。實現 public class listnode public class solution listnode newhead null listn...

反轉鍊錶(c 實現)

template class t class listnode template class t class list 反轉鍊錶 1 1 首先若煉表為空或只有乙個元素,不需要反轉,否則到2 2 定義三個指標p,q,r,p head它們的關係為p q r 3 令q p,若r為尾節點,則令r q,hea...