Skip to content

Instantly share code, notes, and snippets.

@rajubd49
Created August 5, 2019 10:48
Show Gist options
  • Save rajubd49/ce654495280ff1c9e905dc9c2bd25c6e to your computer and use it in GitHub Desktop.
Save rajubd49/ce654495280ff1c9e905dc9c2bd25c6e to your computer and use it in GitHub Desktop.
Swift implementation of Linked List (Insert, Delete, Special insert).
import UIKit
// Linked List (Insert, Delete, Special insert)
class Node {
let value: Int
var nextNode: Node?
init(value:Int, nextNode: Node?) {
self.value = value
self.nextNode = nextNode
}
}
class LinkedList {
var headNode: Node?
// 1. Insert
func insert(value: Int) {
//For first insertion
if headNode == nil {
headNode = Node(value: value, nextNode: nil)
return
}
//For other insertion after the first one
var currentNode = headNode
while currentNode?.nextNode != nil {
currentNode = currentNode?.nextNode
}
//When all insertion done, set the last node value and last nextNode to nil for the end of list
currentNode?.nextNode = Node(value: value, nextNode: nil)
}
// 2. Delete
func delete(value: Int) {
// For first node
if headNode?.value == value {
headNode = headNode?.nextNode
}
//For others
var previousNode: Node?
var currentNode = headNode
while currentNode != nil && currentNode?.value != value {
previousNode = currentNode
currentNode = currentNode?.nextNode
}
previousNode?.nextNode = currentNode?.nextNode
}
// 3. Special insert // Insert in order
func insertInOrder(value: Int) {
if headNode == nil || headNode?.value ?? Int.min >= value {
let newMode = Node(value: value, nextNode: headNode)
headNode = newMode
return
}
var currentNode: Node? = headNode
while currentNode?.nextNode != nil && currentNode?.nextNode?.value ?? Int.min < value {
currentNode = currentNode?.nextNode
}
currentNode?.nextNode = Node(value: value, nextNode: currentNode?.nextNode)
}
func displayListItems() {
print("Items in node:")
var currentNode = headNode
while currentNode != nil {
print(currentNode?.value ?? "")
currentNode = currentNode?.nextNode
}
}
func setupNodes() { // Dummy node, 1->2->3->nil
let three = Node(value: 3, nextNode: nil)
let two = Node(value: 2, nextNode: three)
headNode = Node(value: 1, nextNode: two)
}
}
let linkedList = LinkedList()
//linkedList.setupNodes()
linkedList.insert(value: 1)
linkedList.insert(value: 2)
linkedList.insert(value: 4)
linkedList.insert(value: 5)
linkedList.insertInOrder(value: 3)
//linkedList.delete(value: 2)
linkedList.displayListItems()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment