反转链表主要目的是节省内存空间,不用开辟新的内存空间,在原来的空间进行操作。
若要进行增删操作就可以在具体某个节点进行增删,然后把前后节点拼接在一起,从而组成新的链表。
class LinkNode<Value> {
var val:Value
var next: LinkNode?
init(value: Value, next: LinkNode? = nil) {
self.val = value
self.next = next
}
}
extension LinkNode: CustomStringConvertible {
public var description: String {
guard let next = next else {
return "\(val)"
}
return "\(val) -> " + String(describing: next)
}
}
struct LinkedList<Value> {
var head: LinkNode<Value>?
var last: LinkNode<Value>?
init() {}
var isEmpty: Bool {
return head == nil
}
mutating func initNode() -> LinkNode<Value> {
for index in 5...8 {
self.push(index as! Value)
}
return head ?? LinkNode(value: 0 as! Value)
}
mutating func push(_ value: Value) {
head = LinkNode(value: value, next: head)
if last == nil {
last = head
}
}
mutating func reverse(_ head: LinkNode<Value>?) -> LinkNode<Value>? {
if(head == nil || head?.next == nil){
return head
}
let last = reverse(head?.next)
head?.next?.next = head
head?.next = nil
return last
}
mutating func reverseList(_ head: LinkNode<Value>?) ->
LinkNode<Value>? {
var cur: LinkNode<Value>? = nil
var pre: LinkNode<Value>? = head
while pre != nil {
let temp = pre?.next
pre?.next = cur
cur = pre
pre = temp
}
return cur
}
}
var list = LinkedList<Int>()
//初始链表
let node = list.initNode()
print(node)
//递归实现链表反转
let link = list.reverse(node)
if let linkList = link {
print(linkList)
}
//迭代法实现链表反转
let mewLink = list.reverseList(link)
if let newLink = mewLink {
print(newLink)
}