Posted on by Kalkicode
Code Doubly linked list

Insert node at beginning of doubly linked list in golang

Go program for Insert node at beginning of doubly linked list. Here more information.

package main
import "fmt"
// Go Program For
// insert new node at beginning of doubly linked list

// Define class of linked list Node
type LinkNode struct {
	data int
	next * LinkNode
	prev * LinkNode
}
func getLinkNode(data int) * LinkNode {
	return &LinkNode {data,nil,nil}
}
type DoublyLinkedList struct {
	head * LinkNode
}
func getDoublyLinkedList() * DoublyLinkedList {
	return &DoublyLinkedList {nil}
}
// Insert new node at beginning position
func(this *DoublyLinkedList) insert(value int) {
	// Create a node
	var node * LinkNode = getLinkNode(value)
	node.next = this.head
	// When linked list is not empty
	if this.head != nil {
		this.head.prev = node
	}
	// Make new head
	this.head = node
}
// Display node element of doubly linked list
func(this DoublyLinkedList) display() {
	if this.head == nil {
		fmt.Println("Empty Linked List")
	} else {
		fmt.Println("  Doubly Linked List Element :")
		// Get first node of linked list
		var temp * LinkNode = this.head
		// iterate linked list 
		for (temp != nil) {
			// Display node value
			fmt.Print("  ", temp.data)
			// Visit to next node
			temp = temp.next
		}
	}
}
func main() {
	var dll * DoublyLinkedList = getDoublyLinkedList()
	// Insert following linked list nodes
	dll.insert(70)
	dll.insert(60)
	dll.insert(50)
	dll.insert(40)
	dll.insert(30)
	dll.insert(20)
	dll.insert(10)
	//  NULL <- 10 <--> 20 <--> 30 <--> 40 <--> 50 <--> 60 <--> 70->NULL
	dll.display()
}

Output

Doubly Linked List Element :
10  20  30  40  50  60  70

Comment

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