gpt4 book ai didi

swift - 如何反转 Swift 扩展中的链表?

转载 作者:搜寻专家 更新时间:2023-10-31 08:32:21 25 4
gpt4 key购买 nike

我想反转extension中的单链表,但最后还是失败了。有人能帮帮我吗?谢谢。

   public class List<T: Equatable> {
var value: T!
var nextItem: List<T>?

public convenience init!(_ values: T...) {
self.init(Array(values))
}

init!(var _ values: Array<T>) {
if values.count == 0 {
return nil
}
value = values.removeFirst()
nextItem = List(values)
}
}



// Reverse a linked list.
extension List {
func reverse() {

}
}

最佳答案

我这里有一个解决方案。请阅读评论,从代码中也可以看出这一点。此外,我还通过 CustomStringConvertible 在列表中添加了“描述”,以帮助调试和打印。

public class List<T: Equatable>{
var value: T!
var nextItem: List<T>?

public convenience init!(_ values: T...) {
self.init(Array(values))
}

init!(_ values: Array<T>) {
if values.count == 0 {
return nil
}
var valuesCopy = values
value = valuesCopy.removeFirst()
nextItem = List(Array(valuesCopy))
}



}

extension List : CustomStringConvertible{
public var description: String {
var desc = String()
var listRef : List<T>? = self
while listRef != nil {
desc += "\((listRef?.value)!) "
listRef = listRef?.nextItem
}
return desc
}
}

extension List{
func reverse() -> List?{

// Iterate through each item, and reverse its link until you visit the last node in the list.
// Once you reach the end, All items except the last one would have
// their links reversed.
var nextNode : List<T>? = self.nextItem
var prevNode : List<T>? = nil
var currentNode : List<T>? = self

while nextNode != nil{

currentNode?.nextItem = prevNode
prevNode = currentNode
currentNode = nextNode
nextNode = currentNode?.nextItem
}

//Ensure the last item in the list too has its links reversed.
currentNode?.nextItem = prevNode

return currentNode

}

}

var list = List(1,2,3,5)

print(list ?? "Failed to create the list")


if let reversed = list.reverse(){
print(reversed)
}

关于swift - 如何反转 Swift 扩展中的链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36708041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com