Skip to content

Instantly share code, notes, and snippets.

@tpae
Last active November 10, 2016 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tpae/7fa3956c7d6a1df73a5999b9fef76c5c to your computer and use it in GitHub Desktop.
Save tpae/7fa3956c7d6a1df73a5999b9fef76c5c to your computer and use it in GitHub Desktop.
Merging two LinkedLists in Swift
import Foundation
class Node {
var val: Int
var next: Node?
init(val: Int) {
self.val = val
}
}
class LinkedList {
var root: Node?
func insert(val: Int) {
if self.root == nil {
self.root = Node(val: val)
} else {
self.insert(node: &self.root!, val: val)
}
}
func insert(node: inout Node, val: Int) {
// if val is greater than node
if val > node.val {
if node.next == nil {
node.next = Node(val: val)
} else {
self.insert(node: &node.next!, val: val)
}
} else {
// val is less than node, squeeze in node
let newNode = Node(val: val)
// replace val
newNode.next = node
node = newNode
}
}
func merge(list: LinkedList) {
var listNode = list.root
while listNode != nil {
self.insert(val: listNode!.val)
listNode = listNode!.next
}
}
func printData() {
var node = self.root
while node != nil {
print(node!.val)
node = node!.next
}
}
}
var list = LinkedList()
list.insert(val: 2)
list.insert(val: 4)
list.insert(val: 1)
list.insert(val: 2)
list.insert(val: 0)
var listTwo = LinkedList()
listTwo.insert(val: 3)
listTwo.insert(val: 6)
listTwo.insert(val: 1)
listTwo.insert(val: 0)
list.merge(list: listTwo)
list.printData()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment