-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDay 24; More Linked Lists.swift
62 lines (48 loc) · 1.42 KB
/
Day 24; More Linked Lists.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
import Foundation
// Start of class Node
class Node {
var data: Int
var next: Node?
init(d: Int) {
data = d
}
} // End of class Node
// Start of class LinkedList
class LinkedList {
func insert(head: Node?, data: Int) -> Node? {
if head == nil {
return Node(d: data)
}
head?.next = insert(head: head?.next, data: data)
return head
}
func display(head: Node?) {
if head != nil {
print(head!.data, terminator: " ")
display(head: head?.next)
}
}
// Start of function removeDuplicates
func removeDuplicates(head: Node?) -> Node? {
var dataSet: Set<Int> = []
var currentNode: Node? = head!
var lastNode = head
while currentNode != nil {
defer { currentNode = currentNode?.next }
if dataSet.contains(currentNode!.data) {
lastNode!.next = currentNode?.next
} else {
dataSet.update(with: currentNode!.data)
lastNode = currentNode
}
}
return head
} // End of function removeDuplicates
} // End of class LinkedList
var head: Node?
let linkedList = LinkedList()
let t = Int(readLine()!)!
for _ in 0..<t {
head = linkedList.insert(head: head, data: Int(readLine()!)!)
}
linkedList.display(head: linkedList.removeDuplicates(head: head))