-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.swift
More file actions
62 lines (57 loc) · 1.68 KB
/
LinkedList.swift
File metadata and controls
62 lines (57 loc) · 1.68 KB
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
//
// LinkedList.swift
//
//
// Created by Douglas MacbookPro on 9/11/17.
//
//
import Foundation
//Implementation of LinkedList
class Node<T: Equatable> {
var value: T? = nil
var next: Node? = nil
}
class LinkedList<T: Equatable> {
var head = Node<T>()
func insert(value: T) {
//find to see if empty list
if self.head.value == nil {
self.head.value = value
} else {
//find the last node without a next value
var lastNode = self.head
while lastNode.next != nil {
lastNode = lastNode.next!
}
//once found, create a new node and connect the linked list
let newNode = Node<T>()
newNode.value = value
lastNode.next = newNode
}
}
func remove(value: T) {
//Check if the value is at the head
if self.head.value == value {
self.head = self.head.next!
}
//Traverse the linked list to see if node is in the linked list
if self.head.value != nil {
var node = self.head
var previousNode = Node<T>()
//If value found, exit the loop
while node.value != value && node.next != nil {
previousNode = node
node = node.next!
}
//once found, connect the previous node to the current node's next
if node.value == value {
if node.next != nil {
previousNode.next = node.next
} else {
//if at the end, the next is nil
previousNode.next = nil
}
}
}
}
}