Skip to content

Instantly share code, notes, and snippets.

@alexpaul
Created September 16, 2020 16:37
Show Gist options
  • Save alexpaul/254e83b5cd3ce0289304c536f61a66e6 to your computer and use it in GitHub Desktop.
Save alexpaul/254e83b5cd3ce0289304c536f61a66e6 to your computer and use it in GitHub Desktop.
Reverse a Linked List
// Created by Alex Paul on 9/16/20.
// Copyright © 2020 Alex Paul. All rights reserved.
//
import Foundation
// Reverse a singly linked list.
class Node {
var value: Int
var next: Node?
//var previous: Node?
init(_ value: Int) {
self.value = value
}
}
func printNodeValues(_ node: Node?) {
var node = node
while let currentNode = node {
print(currentNode.value)
node = currentNode.next
}
}
// 3 -> 1 -> 8 -> nil
let nodeOne = Node(3)
let nodeTwo = Node(1)
let nodeThree = Node(8)
nodeOne.next = nodeTwo
nodeTwo.next = nodeThree
printNodeValues(nodeOne) // 3, 1, 8
// in this problem there is pointer manipulation being done
// what does that mean?
// current node point 3 -> 1
// 3 -> 1 -> 8 -> nil
// 8 -> 1 -> 3 -> nil
func reverseList(_ node: Node?) -> Node? {
var node = node // now we can mutate node
var previousNode: Node? // nil - this will be the reverse list returned
var nextNode: Node? // temp Node
while let currentNode = node {
nextNode = currentNode.next
// main part of this problem is the following two lines below:
// this line will be reversing the current next pointer
// ->
// <-
currentNode.next = previousNode
previousNode = currentNode // nil, 3, 1, 8
// keep traversing the list
node = nextNode
}
return previousNode // reverse nodes
}
let modifiedNode = reverseList(nodeOne)
printNodeValues(modifiedNode) // 8, 1, 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment