insert node at beginning of circular linked list in golang
Go program for insert node at beginning of circular linked list. Here problem description and other solutions.
package main
import "fmt"
// Go Program
// Insert node at beginning of circular linked list
// Define struct of linked list Node
type LinkNode struct {
data int
next * LinkNode
}
func getLinkNode(data int, first * LinkNode) * LinkNode {
return &LinkNode {data,first}
}
type CircularLinkedList struct {
head * LinkNode
}
func getCircularLinkedList() * CircularLinkedList {
return &CircularLinkedList {nil}
}
// Insert node at begining of circular linked list
func(this *CircularLinkedList) insert(value int) {
// Create a node
var node * LinkNode = getLinkNode(value, this.head)
if this.head == nil {
// First node of linked list
this.head = node
node.next = this.head
} else {
var temp * LinkNode = this.head
// Find the last node
for (temp.next != this.head) {
// Visit to next node
temp = temp.next
}
// Add node
temp.next = node
// make new head node
this.head = node
}
}
// Display node element of circular linked list
func(this CircularLinkedList) display() {
if this.head == nil {
fmt.Println("Empty Linked List")
} else {
fmt.Println(" Linked List Element : ")
// Get first node
var temp * LinkNode = this.head
// iterate linked list
for (temp != nil) {
// Display node
fmt.Print(" ", temp.data)
// Visit to next node
temp = temp.next
if temp == this.head {
// Stop iteration
return
}
}
}
}
func main() {
var task * CircularLinkedList = getCircularLinkedList()
// Add following linked list nodes
task.insert(8)
task.insert(7)
task.insert(6)
task.insert(5)
task.insert(4)
task.insert(3)
task.insert(2)
task.insert(1)
// Display node
task.display()
}
Output
Linked List Element :
1 2 3 4 5 6 7 8
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