-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedlist.swift
70 lines (58 loc) · 1.42 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
import Foundation
class Node<T: Equatable> {
var next: Node?
let data: T
init(data: T) {
self.data = data
}
}
class LinkedList<T: Equatable>: Sequence {
var head: Node<T>?
func append(data: T) {
guard let _ = head else {
head = Node(data: data)
return
}
tail()?.next = Node(data: data)
}
func prepend(data: T) {
let newHead = Node(data: data)
newHead.next = head
head = newHead
}
func deleteNode(with value: T) {
guard var current = head else { return }
if current.data == value {
head = current.next
return
}
while let next = current.next {
if next.data == value {
current.next = next.next
return
}
current = next
}
}
func makeIterator() -> LinkedListIterator<T> {
return LinkedListIterator<T>(head)
}
private func tail() -> Node<T>? {
var current = head
for node in self {
current = node
}
return current
}
}
class LinkedListIterator<T: Equatable>: IteratorProtocol {
var currentNode: Node<T>?
init(_ node: Node<T>?) {
currentNode = node
}
func next() -> Node<T>? {
let next = currentNode
currentNode = currentNode?.next
return next
}
}