Chapter 4: Linked List

前言

先從linked list登場,不過這章所介紹的只有單向串列,更複雜的雙向串列就需要自己額外延伸了,這章前半部講單向串列基本操作的實作,後半部則是利用Swift standard library中一些以定義的protocol來增加linked list的功能。

大綱

Node

  • Node的結構

    • 含有一個value

    • 含有一個next指標,指向下個node

LinkedList

  • Linked List的結構

    • 將多個Node串接起來

    • 含有一個head指標,指向第一個node

    • 含有一個tail指標,指向最後一個node

push operations

  • 加入一個值到list的最前端

    • 將這個值產生一個node, 並將這個node的next指標指向當前的head

    • 如果沒有tail指標,則tail跟head指向同一個node

append operations

  • 加入一個值到list的最末端

    • 如果當前list是空的,可以直接做之前push的動作

    • 把tail next指向當前新增的node

    • 再把tail移動到新增的node

insert(after:) operations

  • 插入值在某個index的node後面

    • 先找出對應index的node

    • 插入新的node

Performance analysis

  • push, append, insert這3個動作,都是針對next指標進行操作,所以都是0(1)

  • node(at index: Int), 這個動作是從head開始往後遍歷尋找,所以會依據index大小,而遞增尋找時間。

pop operations

  • 移除list中最前端的node。

    • 把head指標移到當前的head的next指標。

removeLast operations

  • 移除list最末端的元素

  • 這個是所有list操作中比較複雜,原因是在處理tail,移除最後一個元素,就是把tail指標指向的node移掉,這是沒問題,但移掉後,tail要怎麼指向在原本list倒數第二個元素(最後元素已經被移除),因爲node結構並沒有前一個node資訊,所以需要兩個指針由head往後遍歷,直到有個指針可以指到list中倒數第二個node。

remove(after:) operations

  • 這個跟Inset after動作很像,也是要先找到要刪除index的node。

Performance analysis

  • 因為removeLast是利用兩個指針從頭開始到,所需要找到倒數第二個node,需要O(n),其他都是指針的處理。

Swift collection protocols

OK, 這章前半部,基本就是實作了所有linked list的基本操作,接下來,就要利用Swift的特色,讓linked list有更多功能。

  • Tier 1, Sequence:

    • A sequence type provides sequential access to its elements. This axiom comes with a caveat: Using the sequential access may destructively consume the elements.

  • Tier 2, Collection:

    • A collection type is a sequence type that provides additional guarantees. A collection type is finite and allows for repeated nondestructive sequential access.

  • Tier 3, BidirectionalColllection:

    • A collection type can be a bidirectional collection type if it, as the name suggests, can allow for bidirectional travel up and down the sequence. This isn’t possible for the linked list, since you can only go from the head to the tail, but not the other way around.

  • Tier 4, RandomAccessCollection:

    • A bidirectional collection type can be a random access collection type if it can guarantee that accessing an element at a particular index will take just as long as access an element at any other index. This is not possible for the linked list, since accessing a node near the front of the list is substantially quicker than one that is further down the list.

針對linked list

First, since a linked list is a chain of nodes, adopting the Sequence protocol makes sense.

Second, since the chain of nodes is a finite sequence, it makes sense to adopt the Collection protocol

Becoming a Swift collection

Value semantics and copy-on-write

  • copy-on-write是Swift非常重要的特色。是assine by value, 不是assign by reference。

Optimizing COW

每個操作並不一定都要執行copy動作,只有當出現assing動作才需要執行copy動作,可以透過isKnownUniquelyReferenced來判斷是否有assign動作。

Last updated