Swift 链表 LinkedList

一个链表就是一串节点(Node). 每个Node有两个责任:

  1. 持有一个value
  2. 持有下一个Node的引用。nil表示链表最后一个Node

先写一个工具方法方便打印

func example(of desc: String,block: (()->Void)){
  print("---Example of \(desc)---")
  block()
}

创建一个基本的Node类, 并重写description

public class Node<Value> {
  public var value: Value
  public var next: Node?
  
  public init(value: Value,next: Node? = nil) {
    self.value = value
    self.next = next
  }
}
extension Node: CustomStringConvertible {
  public var description: String {
    guard let next = next else {
      return "\(value)"
    }
    return "\(value) -> " + String(describing: next)
  }
}

尝试创建几个Node并将他们链接起来。

example(of: "creating and linking nodes") {
  let node1 = Node(value: 1)
  let node2 = Node(value: 2)
  let node3 = Node(value: 3)
  
  node1.next = node2
  node2.next = node3
  
  print(node1)
}

控制台输出

---Example of creating and linking nodes---
1 -> 2 -> 3

这个离我们想要的还差很远,如果list比较长,创建起来将会是灾难性的。所以我们应该用一个LinkedListNode管理起来。

创建LinkList

public struct LinkedList<Value> {
  
  public var head: Node<Value>?
  public var tail: Node<Value>?
  public init(){}
  
  public var isEmpty: Bool {
    return head == nil
  }
}

extension LinkedList: CustomStringConvertible {

  public var description: String {
    guard let head = head else {
      return "Empty list"
    }
    return String(describing: head)
  }
}

一个LinkedList 只需要知道头和尾,就能确定整个链表。
如何给链表添加数据呢,三种方式:

  • push: 从head处添加
  • append: 从tail处添加
  • insert(after:) 指定位置添加

push 操作

extension LinkedList {
  public mutating func push(_ value: Value) {
    head = Node(value: value, next: head)
    if tail == nil {
      tail = head
    }
  }
}

从头部添加很简单,只需要重新设置head并将之前的head设置为next,考虑到链表元素只有一个的情况。tail即使head

example(of: "push") {
  var list = LinkedList<Int>()
  list.push(3)
  list.push(2)
  list.push(1)
  
  print(list)
}

// result: 
---Example of push---
1 -> 2 -> 3

append 操作

extension LinkedList {
  
  public mutating func append(_ value: Value){
    guard !isEmpty else {
      push(value)
      return
    }
    tail?.next = Node(value: value)
    tail = tail?.next
  }
}

首先考虑链表为空的情况,如果不为空则直接将Node赋值给当前的tail?.next,而此Node也作为新的tail

example(of: "append") {
  var list = LinkedList<Int>()
  list.append(1)
  list.append(2)
  list.append(3)
  
  print(list)
}
// result: 
---Example of append---
1 -> 2 -> 3

insert(after:) 操作

再新增一个便利方法node(at:)

extension LinkedList {
  
  // 只有空list或者index超过边界才会返回nil
  public func node(at index: Int) -> Node<Value>? {
    var currentNode = head
    var currentIndex = 0
    while currentNode != nil && currentIndex < index {
      currentNode = currentNode?.next
      currentIndex += 1
    }
    return currentNode
  }
  
  @discardableResult
  public mutating func insert(_ value: Value, after node: Node<Value>) -> Node<Value> {
    guard tail !== node else {
      append(value)
      return tail!
    }
    node.next = Node(value: value, next: node.next)
    return node.next!
  }
}

insert(after:)的思想也很简单,如果传进来的Node就是tail,则相当于执行一个append。剩下就是把传进来的Node的next设置为value, value的next设置为node.next

example(of: "inserting at a particular index") {
  var list = LinkedList<Int>()
  list.push(3)
  list.push(2)
  list.push(1)
  
  print("Before inserting: \(list)")
  var middleNode = list.node(at: 1)!
  for _ in 1...4 {
    middleNode = list.insert(-1, after: middleNode)
  }
  print("After inserting: \(list)")
}
// result: 
---Example of inserting at a particular index---
Before inserting: 1 -> 2 -> 3
After inserting: 1 -> 2 -> -1 -> -1 -> -1 -> -1 -> 3

方法性能分析

方法 时间复杂度
push O(1)
append O(1)
insert(after:) O(1)
node(at:) O(i) i表示给定的index

性能看起来都不错。

从链表中删除数据

也是三个方法

  • pop 从表头删除
  • removeLast 从结尾删除
  • remove(after:) 任意位置删除

pop 操作

push一样 非常简单。

extension LinkedList {
  
  public mutating func pop() -> Value?{
    defer {
      head = head?.next
      if isEmpty {
        tail = nil
      }
    }
    return head?.value
  }
}

如果是只有一个元素或者空元素的列表head?.next就为nil。这时候需要设置tailnil

example(of: "pop") {
  var list = LinkedList<Int>()
  list.push(3)
  list.push(2)
  list.push(1)
  
  print("Before popping list: \(list)")
  let poppedValue = list.pop()
  print("After popping list: \(list)")
  print("Popped value: " + String(describing: poppedValue))
}
// result: 
---Example of pop---
Before popping list: 1 -> 2 -> 3
After popping list: 2 -> 3
Popped value: Optional(1)

removeLast 操作

这个方法会有点麻烦,我们虽然保存了tail但是并不知道tail的上一个元素。所以这里只能用遍历的方法

extension LinkedList {
  
  public mutating func removeLast() -> Value? {
    guard let head = head else {
      return nil
    }
    guard head.next != nil else {
      // 只有一个元素的情况
      return pop()
    }
    var prev = head
    var current = head
    // 循环取next直到没有next
    while let next = current.next {
      prev = current
      current = next
    }
    prev.next = nil
    tail = prev
    return current.value
  }
}

注释已经很清楚了。

example(of: "removing the last node") {
  var list = LinkedList<Int>()
  list.push(3)
  list.push(2)
  list.push(1)

  print("Before removing last node: \(list)")
  let removedValue = list.removeLast()

  print("After removing last node: \(list)")
  print("Removed value: " + String(describing: removedValue))
}
// result: 
---Example of removing the last node---
Before removing last node: 1 -> 2 -> 3
After removing last node: 1 -> 2
Removed value: Optional(3)

removeLast需要把整个list遍历一遍,所以这里的时间复杂度为 O(n)

remove(after:) 操作

这个跟insert(after:)差不多,都是比较简单

extension LinkedList {
  
  @discardableResult
  public mutating func remove(after node: Node<Value>) -> Value? {
    defer {
      if node.next === tail {
        tail = node
      }
      node.next = node.next?.next
    }
    return node.next?.value
  }
}

如果移除的Node的下一个是tail,直接将tail设置为此node。并将node的下一个设置为下下个。

example(of: "removing a node after a particular node") {
  var list = LinkedList<Int>()
  list.push(3)
  list.push(2)
  list.push(1)
  
  print("Before removing at particular index: \(list)")
  let index = 1
  let node = list.node(at: index - 1)!
  let removedValue = list.remove(after: node)
  
  print("After removing at index \(index): \(list)")
  print("Removed value: " + String(describing: removedValue))
}

// result: 
---Example of removing a node after a particular node---
Before removing at particular index: 1 -> 2 -> 3
After removing at index 1: 1 -> 3
Removed value: Optional(2)

方法性能分析

方法 时间复杂度
pop O(1)
removeLast O(n)
remove(after:) O(1)

swifty的方式

Collection protocol提供了很多便利的方式去访问和操作列表。这里也可以让自己的LinkedList实现Collection 协议。

因为链表操作的是Node,所以我们的Index需要自定义下。


extension LinkedList: Collection {
  
  public struct Index: Comparable {
    
    public var node: Node<Value>?
    
    static public func == (lhs: Index, rhs: Index) -> Bool{
      switch (lhs.node,rhs.node) {
      case let (left?,right?):
        return left.next === right.next
      case (nil,nil):
        return true
      default:
        return false
      }
    }
    
    static public func < (lhs: Index,rhs: Index) -> Bool {
      guard lhs != rhs else {
        return false
      }
      let nodes = sequence(first: lhs.node) { $0?.next }
      return nodes.contains(where: { $0 === rhs.node })
    }
  }
  
  public var startIndex: Index {
    return Index(node: head)
  }
  
  public var endIndex: Index {
    return Index(node: tail?.next)
  }
  
  public func index(after i: Index) -> Index {
    return Index(node: i.node?.next)
  }
  
  public subscript(position: Index) -> Value {
    return position.node!.value
  }
}

这里Index持有Node并实现 Comparable协议 。 再实现Collection 的几个必要的方法。就可以使用了。

example(of: "using collection") {
  var list = LinkedList<Int>()
  for i in 0...0{
    list.append(i)
  }
  print("List: \(list)")
  print("First element: \(list[list.startIndex])")
  print("Array containing first 3 elements: \(Array(list.prefix(3)))")
  print("Array containing last 3 elements: \(Array(list.suffix(3)))")

  let sum = list.reduce(0, +)
  print("Sum of all values: \(sum)")
}

// result: 
---Example of using collection---
List: 0
First element: 0
Array containing first 3 elements: [0]
Array containing last 3 elements: [0]
Sum of all values: 0

Swift中的Collection为值类型,使用copy-on-write机制实现的。

例子:

example(of: "array cow") {
  let array1 = [1, 2]
  var array2 = array1
  
  print("array1: \(array1)")
  print("array2: \(array2)")
  
  print("---After adding 3 to array 2---")
  array2.append(3)
  print("array1: \(array1)")
  print("array2: \(array2)")
}

// result: 
---Example of array cow---
array1: [1, 2]
array2: [1, 2]
---After adding 3 to array 2---
array1: [1, 2]
array2: [1, 2, 3]

这里可以看到array2执行append方法,列表改变了,但是array1并没有改变。这是值类型的特质。array2 本质是在 append 方法调用的时候才真正copy。在append方法执行前,array1array2都指向同一个地址。

再来看下LinkedList

example(of: "linked list cow") {
  var list1 = LinkedList<Int>()
  list1.append(1)
  list1.append(2)
  var list2 = list1
  print("List1: \(list1)")
  print("List2: \(list2)")
  
  print("After appending 3 to list2")
  list2.append(3)
  print("List1: \(list1)")
  print("List2: \(list2)")
}

// result: 
---Example of linked list cow---
List1: 1 -> 2
List2: 1 -> 2
After appending 3 to list2
List1: 1 -> 2 -> 3
List2: 1 -> 2 -> 3

我们自己写的链表并没有值类型的特质,是因为我们的Node是使用class(引用类型)实现的。

一个方法就是在我们每次操作新增或者删除某个Node之前,将所有元素更新一遍

extension LinkedList {
  
  private mutating func copyNodes(){
    guard var oldNode = head else {
      return
    }
    head = Node(value: oldNode.value)
    var newNode = head
    while let nextOldNode = oldNode.next {
      newNode?.next = Node(value: nextOldNode.value)
      newNode = newNode?.next
      oldNode = nextOldNode
    }
    tail = newNode
  }
  
}

在所有包含mutating的方法前调用copyNodes 。但是这样相当于在所有方法时间复杂度前提下增加了一个O(n)。明显是不可接受的。

所以这里还可以对此进行优化。

  • isKnownUniquelyReferenced

isKnownUniquelyReferenced方法可以判断是否只有被一个对象引用。没有共享,这样我们只需要在两个对象同时引用的情况下才需要使用值类型的特点。
copyNodes最上面加上

guard !isKnownUniquelyReferenced(&head) else {
    return
}

这样大部分情况下就不会复制。

  • 对方法进行评估

push方法并不会造成两者不一样。

example(of: "linked list cow") {
  var list1 = LinkedList<Int>()
  list1.append(1)
  list1.append(2)
  var list2 = list1
  print("List1: \(list1)")
  print("List2: \(list2)")
  
  print("After appending 3 to list2")
  list2.push(0)
  print("List1: \(list1)")
  print("List2: \(list2)")
}
// result: 
---Example of linked list cow---
List1: 1 -> 2
List2: 1 -> 2
After appending 3 to list2
List1: 1 -> 2
List2: 0 -> 1 -> 2

所以在push中并不需要调用copyNodes


参考自《Data Structure & Algorithms in Swift》

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容