Insert node at beginning of linked list in golang
Write a program which is create and add new node at the beginning of linked list in Go.

Here given of code implementation process.
package main
import "fmt"
/*
Go program for
Insert node at beginning of linked list
*/
// Linked list node
type LinkNode struct {
data int
next * LinkNode
}
func getLinkNode(data int) * LinkNode {
var me *LinkNode = &LinkNode {}
me.data = data
me.next = nil
return me
}
type SingleLL struct {
head * LinkNode
}
func getSingleLL() * SingleLL {
var me *SingleLL = &SingleLL {}
me.head = nil
return me
}
// Adding new node at beginning of linked list
func(this *SingleLL) addNode(data int) {
// Create new node
var node * LinkNode = getLinkNode(data)
// Connect current node to previous head
node.next = this.head
this.head = node
}
// Display linked list element
func(this SingleLL) display() {
if this.head == nil {
return
}
var temp * LinkNode = this.head
// iterating linked list elements
for (temp != nil) {
fmt.Print( temp.data, " → ")
// Visit to next node
temp = temp.next
}
fmt.Print(" NULL\n")
}
func main() {
var sll * SingleLL = getSingleLL()
// Linked list
// 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
sll.addNode(8)
sll.addNode(7)
sll.addNode(6)
sll.addNode(5)
sll.addNode(4)
sll.addNode(3)
sll.addNode(2)
sll.addNode(1)
sll.display()
}
1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
Time complexity of above program is O(1).
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment