大家好,又见面了,我是你们的朋友全栈君。
翻转链表
复制代码
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
复制代码
extension ListNode: CustomDebugStringConvertible, CustomStringConvertible{
public var description: String{
var items:[Int] = [Int]()
var tmp: ListNode? = self
while tmp != nil {
items.append(tmp!.val)
tmp = tmp!.next
}
return "\(items)"
}
public var debugDescription: String{
return "debug:\(description)"
}
}
extension Array {
var listNode: ListNode?{
var node: ListNode?
var tmp: ListNode?
for item in self as! [Int] {
if node == nil {
node = ListNode.init(item)
tmp = node
}else{
tmp!.next = ListNode.init(item)
tmp = tmp?.next
}
}
return node
}
}
复制代码
func reverseListNode(_ listNode: ListNode?)->ListNode?{
let tmpListNode = listNode
if tmpListNode == nil {
return listNode
}else{
var currentNode = tmpListNode
var nextNode = tmpListNode?.next
currentNode?.next = nil
while nextNode != nil {
let tmp = nextNode?.next
nextNode?.next = currentNode
currentNode = nextNode
nextNode = tmp
}
return currentNode
}
}
复制代码
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/126361.html原文链接:https://javaforall.cn