Skip to content

Instantly share code, notes, and snippets.

@spurscho
Created January 7, 2020 08:55
Show Gist options
  • Save spurscho/49b0d1e04e42d95178ad9bea6f4f0e2b to your computer and use it in GitHub Desktop.
Save spurscho/49b0d1e04e42d95178ad9bea6f4f0e2b to your computer and use it in GitHub Desktop.
Sample Linked List.swift
import UIKit
class Node {
let value: Int
var next: Node?
init(_ value:Int, _ next: Node?) {
self.value = value
self.next = next
}
}
class LinkedList {
var head: Node?
func displayListItems() {
print("Here is whats inside of your list:")
var current = head
while current != nil {
print(current?.value ?? "")
current = current?.next
}
}
func insert(_ value: Int) {
// empty list
if head == nil {
head = Node(value, nil)
return
}
var current = head
while current?.next != nil {
current = current?.next
}
current?.next = Node(value, nil)
}
func delete(_ value: Int) {
if head?.value == value {
head = head?.next
}
var prev: Node?
var current = head
while current != nil && current?.value != value {
prev = current
current = current?.next
}
prev?.next = current?.next
}
func setupDummyNodes() {
let three = Node(3, nil)
let two = Node(2, three)
head = Node(1, two)
}
}
let sampleList = LinkedList()
//sampleList.setupDummyNodes()
sampleList.insert(1)
sampleList.insert(2)
sampleList.insert(3)
sampleList.delete(3)
sampleList.displayListItems()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment