Skip to content

Instantly share code, notes, and snippets.

@kellylougheed
Created January 24, 2021 18:47
Show Gist options
  • Save kellylougheed/f4d02a07386ea13fc83c35dc33c8230e to your computer and use it in GitHub Desktop.
Save kellylougheed/f4d02a07386ea13fc83c35dc33c8230e to your computer and use it in GitHub Desktop.
Linked list implementation in Swift
class Node {
var value: String
var next: Node?
init(value: String, next: Node? = nil) {
self.value = value
self.next = next
}
}
var ari = Node(value: "Ari")
var malcolm = Node(value: "Malcolm", next: ari)
var pete = Node(value: "Pete", next: malcolm)
var ricky = Node(value: "Ricky", next: pete)
var sean = Node(value: "Sean", next: ricky)
var calvin = Node(value: "Calvin", next: pete)
ricky.next = calvin
// Print the list
var currentNode: Node? = sean
while (currentNode != nil) {
print(currentNode?.value ?? "")
currentNode = currentNode?.next
}
// Reverse the list
currentNode = sean
var nextPrevious: Node?
var previous: Node?
while (currentNode != nil) {
// get and store the next node to use it later as a previous value
nextPrevious = currentNode?.next
// switch the pointer to the next node of the previous value
currentNode?.next = previous
// previous stores the value of the current node
previous = currentNode
// the current node becomes the former next node (now the previous node)
currentNode = nextPrevious
}
// Print the list
print("reversed")
currentNode = ari
while (currentNode != nil) {
print(currentNode?.value ?? "")
currentNode = currentNode?.next
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment