Reverse a Singly Linked List
[cs
challenges
]
And, since we already have a singly linked list, let’s try to reverse it.
Let’s consider the very basic structure of a linked list to help us find a solution. In essence, we have just a chain of nodes, each one pointing pointing to the next, and the special case is the last one in the chain (the tail). We indicate the special case by setting the next pointer to nil
Node(1)->Node(2)->Node(3)->Node(4)->Node(5)->Node(6)->Node(7)->Node(8)->Node(9)->Node(10)->nil
The brute force solution would be to traverse the entire linked list until we get to the tail, preserving each step in a data structure (perhaps a stack) and then, produce a new list with the items in the reverse order. Obviously, we would be increasing the space complexity. But let’s get back to the print-out. To reverse the linked list all we need to do is to flip the direction of the arrows.
func reversed() {
guard let head = self.head else {
return
}
var previousNode:NodeType? = nil
var currentNode:NodeType? = head
var nextNode:NodeType? = nil
while currentNode != nil {
// if there is a `next` node, we keep moving
if let next = currentNode?.next {
nextNode = next
} else {
// but if we are at the last node, we reset the head of the list
self.head = currentNode
nextNode = nil
}
// Let's change the direction of the next pointer arrow
// In the first loop, `previousNode` marking the sentinel of the reversed list
currentNode?.next = previousNode
// and now, prev is pointing to current, and we move on
previousNode = currentNode
currentNode = nextNode
}
}
A working playground is waiting in gist.