This blog post is a part of a series on programming interview questions. In the post, you will learn how to reverse a linked list. You can find more interview questions blog post here.
A common question that comes up in coding interviews is to reverse a linked list. In this post, I will show one way to reverse a linked list.
Here is an example linked list of integers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
type List struct { head *Node tail *Node } // Get head / first func (list *List) First() *Node { return list.head } // Add to tail func (list *List) Add(value int) { newNode := &Node{data: value} if list.head == nil { list.head = newNode } else { list.tail.next = newNode } list.tail = newNode } |
The code below is one solution for reversing a linked list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
func reverse(list *List) { // Set current node to head. var currentNode = list.head // Set nexNode and prevNode to nil. var nextNode *Node = nil var prevNode *Node = nil // Loop from currentNode to nil. for currentNode != nil { // Set nextNode to currentNode.next. nextNode = currentNode.next // Set currentNode.next to prevNode currentNode.next = prevNode // Set prevNode to currentNode. prevNode = currentNode // Set currentNode to nextNode. currentNode = nextNode } // set head to prevNode list.head = prevNode } |
In this blog post, you learned how to reverse a linked list. You can learn more about linked lists at GeeksforGeeks.
Harrison Brock is a software engineer that focuses on Full Stack web development