/// Linked List's Node Class Declaration class LinkedListNode { var value: Int var next: LinkedListNode? public init(_ value: Int) { self.value = value self.next = nil } }
链表的接本结构:
1 2 3 4
class LinkedList { var head: LinkedListNode? // 头结点 var tail: LinkedListNode? // 尾结点 }
常用操作
先在已经定义好了链表及结点的基本结构了,下面我们可以对链表做一些常见的操作。
增加
尾插法
1 2 3 4 5 6 7 8 9 10
func appendToTail(_ value: Int) { let newNode = LinkedListNode(value) if let last = tail { last.next = newNode tail = last.next } else { head = newNode tail = head } }
头插法
1 2 3 4 5 6 7 8 9 10
func appendToHead(_ value: Int) { let newNode = LinkedListNode(value) if let first = head { newNode.next = first head = newNode } else { head = newNode tail = head } }
// 给链表增加了一个长度属性 var length: Int { get { var num = 0 var temp: LinkedListNode? = head while let node = temp { num += 1 temp = node.next } return num } }
func appned(_ value: Int, _ index: Int) { if length == 0 { // 链表本身为空,直接添加 appendToHead(value) } else if index == 0 { // 插入到头结点位置 let newNode = LinkedListNode(value) newNode.next = head head = newNode } else if index < length && index > 0 { // 找到需要插入位置的前一个结点 let newNode = LinkedListNode(value) var temp = 1 var tempNode: LinkedListNode? = head while let node = tempNode { if temp == index { newNode.next = node.next node.next = newNode break } tempNode = tempNode?.next temp += 1 } } }
// 查找某个结点 func node(at index: Int) -> LinkedListNode? { if length == 0 { return nil } else if index >= 0 && index < length { var tempNode = head var j = 0 while tempNode?.next != nil && j < index { tempNode = tempNode?.next j += 1 } return tempNode } return nil }
// 根据值查找 func nodes(_ value: Int) -> [LinkedListNode] { var result: [LinkedListNode] = [] var tempNode = head while let node = tempNode { if node.value == value { result.append(node) } tempNode = node.next } return result }
反转
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
func reverse(_ head: LinkedListNode?) -> LinkedListNode? { if head == nil || head?.next == nil { return head } // 递归找到最后一个结点 let newHead = reverse(head?.next) // 将最后一个结点前一个结点反转 head?.next?.next = head // 断开最后一个结点 head?.next = nil self.head = newHead return newHead }
// 打印链表 func printSelf() { var tempNode = head while let node = tempNode { print(node.value) tempNode = tempNode?.next } }
func map(transform: (Int) -> Int) -> LinkedList { let result = LinkedList() var tempNode = head while let node = tempNode { result.appendToTail(transform(node.value)) tempNode = node.next } return result } func filter(predicate: (Int) -> Bool) -> LinkedList { let result = LinkedList() var tempNode = head while let node = tempNode { if predicate(node.value) { result.appendToTail(node.value) } tempNode = node.next } return result }