-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLinkedList.swift
146 lines (115 loc) · 3.23 KB
/
LinkedList.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import UIKit
struct LinkedList<Value> {
var head: Node<Value>?
var tail: Node<Value>?
var isEmpty: Bool {
return head == nil
}
mutating func push(_ value: Value) {
head = Node(value: value, next: head)
if tail == nil {
tail = head
}
}
mutating func append(_ value: Value) {
guard !isEmpty else {
push(value)
return
}
let node = Node(value: value)
tail!.next = node
tail = node
}
func node(at index: Int) -> Node<Value>? {
var currentIndex = 0
var currentNode = head
while (currentNode != nil && currentIndex < index) {
currentNode = currentNode?.next
currentIndex += 1
}
return currentNode
}
func insert(_ value: Value, after node: Node<Value>) {
node.next = Node(value: value, next: node.next)
}
mutating func pop() -> Value? {
defer {
head = head?.next
if isEmpty {
tail = nil
}
}
return head?.value
}
mutating func removeLast() -> Value? {
guard let head = head else {
return nil
}
guard head.next != nil else {
return pop()
}
var prev = head
var current = head
while let next = current.next {
prev = current
current = next
}
prev.next = nil
tail = prev
return current.value
}
mutating func remove(after node: Node<Value>) -> Value? {
defer {
if node.next === tail {
tail = node
}
node.next = node.next?.next
}
return node.next?.value
}
init() { }
}
extension LinkedList: CustomStringConvertible {
var description: String {
guard let head = head else {
return "Empty List"
}
return String(describing: head)
}
}
class Node<Value> {
var value: Value
var next: Node?
init(value: Value, next: Node? = nil) {
self.value = value
self.next = next
}
}
extension Node: CustomStringConvertible {
var description: String {
guard let next = next else {
return "\(value)"
}
return "\(value) -> " + String(describing: next) + " "
}
}
var list = LinkedList<Int>()
list.push(2)
list.push(22)
print(list) //22 -> 2
list.append(10)
list.append(5)
print(list) //22 -> 2 -> 10 -> 5
let middleNode = list.node(at: 1)!
list.insert(999, after: middleNode)
print(list) //22 -> 2 -> 999 -> 10 -> 5
let newNode = list.node(at: 3)!
list.insert(99, after: newNode)
print(list) //22 -> 2 -> 999 -> 10 -> 99 -> 5
list.pop()
print(list) //2 -> 999 -> 10 -> 99 -> 5
list.removeLast()
print(list) //2 -> 999 -> 10 -> 99
let node = list.node(at: 0)!
let removedValue = list.remove(after: node)
print(list) //2 -> 10 -> 99