翻轉鏈表
複製代碼
鏈表定義
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
複製代碼
extension方便測試觀察
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
}
}
複製代碼