Effectively insert node at beginning of circular linked list in golang

Go program for Effectively insert node at beginning of circular linked list . Here more information.

package main
import "fmt"
// Go Program 
// Insert node at beginning of circular linked list
// Using head and tail nodes

// Define class of linked list Node
type LinkNode struct {
	data int
	next * LinkNode
}
func getLinkNode(data int, first * LinkNode) * LinkNode {
	// Set node value
	return &LinkNode {data, first}
}
type CircularLinkedList struct {
	head * LinkNode
	tail * LinkNode
}
func getCircularLinkedList() * CircularLinkedList {
	return &CircularLinkedList {nil,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.tail == nil {
		// First node of linked list
		this.tail = node
	}
	// Make new head
	this.head = node
	// Connecting the last node to the top of the next field
	this.tail.next = this.head
}
// Display node element of circular linked list
func(this CircularLinkedList) display() {
	if this.head == nil {
		fmt.Println("Empty Linked List")
	} else {
		fmt.Print("Linked List Element :")
		var temp * LinkNode = this.head
		// iterate linked list
		for (temp != nil) {
			// Display node
			fmt.Print("  ", temp.data)
			if temp == this.tail {
				// Stop iteration
				// Or break
				return
			}
			// Visit to next node
			temp = temp.next
		}
	}
}
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







© 2021, kalkicode.com, All rights reserved