- Learn Data Structures and Algorithms with Golang
- Bhagvan Kommadi
- 187字
- 2021-06-24 15:37:47
The AddToHead method
The AddToHead method of the doubly LinkedList class sets the previousNode property of the current headNode of the linked list to the node that's added with property. The node with property will be set as the headNode of the LinkedList method in the following code:
//AddToHead method of LinkedList
func (linkedList *LinkedList) AddToHead(property int) {
var node = &Node{}
node.property = property
node.nextNode = nil
if linkedList.headNode != nil {
node.nextNode = linkedList.headNode
linkedList.headNode.previousNode = node
}
linkedList.headNode = node
}
The example output after the AddToHead method was invoked with property 3 is as follows. A node with property 3 is created. The headNode property of the list has a property value of 1. The current node with property 3 has a nextNode property of nil. The nextNode property of the current node is set to headNode with a property value of 1. The previous node of the headNode property is set to the current node:
Let's take a look at the AddAfter method in the next section.