Skip to content

Instantly share code, notes, and snippets.

@davidinga
Last active May 30, 2019 17:12
Show Gist options
  • Save davidinga/e5136e22cc14a6fc539a1a3622cbeb9f to your computer and use it in GitHub Desktop.
Save davidinga/e5136e22cc14a6fc539a1a3622cbeb9f to your computer and use it in GitHub Desktop.
Singly Linked List
public class SinglyLinkedList<Element> {
private var head: SinglyLinkedListNode<Element>?
private var tail: SinglyLinkedListNode<Element>?
public var isEmpty: Bool {
return head == nil
}
public var count: Int {
var node = head
var count = 0
while node != nil {
count += 1
node = node!.next
}
return count
}
public var first: SinglyLinkedListNode<Element>? {
return head
}
public var last: SinglyLinkedListNode<Element>? {
return tail
}
public func append(_ element: Element) {
let newNode = SinglyLinkedListNode(element)
if tail != nil {
tail!.next = newNode
} else {
head = newNode
}
tail = newNode
}
public func index(of element: Int) -> SinglyLinkedListNode<Element>? {
if element < 0, head == nil {
return nil
}
var node = head
for _ in 0..<element {
node = node!.next
}
return node
}
public func removeAll() {
head = nil
tail = nil
}
public func remove(at index: Int) -> Element? {
//TODO: Remove prevNode and nextNode
var node = head
var prevNode = node
var nextNode = node
var element: Element?
for i in 0...index {
if i == index {
// Element to remove is head.
if index == 0 {
head = head!.next
}
// Element to remove is tail.
else if node!.next == nil {
tail = prevNode
tail!.next = nil
}
// Element to remove is in between head and tail.
else if let next = node!.next {
nextNode = next
prevNode!.next = nextNode
}
element = node!.element
} else {
prevNode = node
}
node = node!.next
}
return element
}
public func remove(node: SinglyLinkedListNode<Element>) -> SinglyLinkedListNode<Element>? {
// Find previous node
var prev = head
while prev! != node {
prev = prev!.next
}
let next = node.next
// Removing element inbetween head and tail
if let prev = prev {
prev.next = next
} else {
// Removing head
head = next
}
// Removing tail
if next == nil {
tail = prev
}
node.next = nil
return node
}
}
public class SinglyLinkedListNode<Element> {
public var element: Element
public var next: SinglyLinkedListNode<Element>?
init(_ element: Element) {
self.element = element
}
}
extension SinglyLinkedListNode: Equatable {
public static func == (lhs: SinglyLinkedListNode, rhs: SinglyLinkedListNode) -> Bool {
return
lhs.next == rhs.next
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment