Skip to content

Instantly share code, notes, and snippets.

@thexande
Created January 21, 2018 02:41
Show Gist options
  • Save thexande/d127ce4ff23dbc4513075a5c45f71a1c to your computer and use it in GitHub Desktop.
Save thexande/d127ce4ff23dbc4513075a5c45f71a1c to your computer and use it in GitHub Desktop.
A quick and dirty reversed linked list implementation in swift 4.
// Reverse Linked List
class Node {
let value: Int
var next: Node?
init(value: Int, next: Node?) {
self.value = value
self.next = next
}
}
let threeNode = Node(value: 3, next: nil)
let twoNode = Node(value: 2, next: threeNode)
let oneNode = Node(value: 1, next: twoNode)
func printList(head: Node?) {
print("Printing out list of nodes")
var currentNode = head
while currentNode != nil {
print(currentNode?.value ?? -1)
currentNode = currentNode?.next
}
}
func reverseList(head: Node?) -> Node? {
var currentNode = head
var previous: Node?
var next: Node?
while currentNode != nil {
next = currentNode?.next
currentNode?.next = previous
previous = currentNode
currentNode = next
}
return previous
}
let reversedList = reverseList(head: oneNode)
printList(head: reversedList)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment