-
Notifications
You must be signed in to change notification settings - Fork 48
/
LoopLinkedList.swift
89 lines (80 loc) · 2.04 KB
/
LoopLinkedList.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//
// LoopLinkedList.swift
// LinkedList
//
// Created by ggl on 2019/3/28.
// Copyright © 2019年 ggl. All rights reserved.
// 循环链表
import Foundation
class LoopLinkedList {
var head: Node?
/// 添加结点
///
/// - Parameter node: 新节点
func addNode(_ data: Int) {
let node = Node(data: data, next: nil)
guard let tailNode = self.tailNode() else {
// 空链表
head = node
node.next = head
return
}
// 非空链表
tailNode.next = node
node.next = head
}
@discardableResult
func deleteNode(_ data: Int) -> Bool {
// 空链表
if head == nil {
return false
}
// 头结点是否是要删除的结点
if head?.data == data {
head = head?.next
let tailNode = self.tailNode()
tailNode?.next = head
return true
}
// 前后指针
var preNode = head
var curNode = head?.next
while curNode != head {
if curNode?.data == data {
preNode?.next = curNode?.next
return true
}
preNode = curNode
curNode = curNode?.next
}
return false
}
/// 获取链表的最后一个结点
///
/// - Returns: 尾结点
func tailNode() -> Node? {
// 判断是否是空链表
if head == nil {
return nil
}
// 尾结点
var tailNode = head
while tailNode?.next != head {
tailNode = tailNode?.next
}
return tailNode
}
/// 打印链表
func print() {
var curNode = head
while curNode != nil {
if curNode?.next == head {
Swift.print(curNode!.data)
break
} else {
Swift.print(curNode!.data, terminator: " -> ")
curNode = curNode?.next
}
}
}
}