implement queue using linked list in golang

Go program for implement queue using linked list. Here more information.

package main
import "fmt"
/*
  Go Program for
  Implement queue using linked list
*/
// Create Q node
type QNode struct {
	data int
	next * QNode
}
func getQNode(value int) * QNode {
	// return new QNode
	return &QNode {
		value,
		nil,
	}
}
type MyQueue struct {
	head * QNode
	tail * QNode
	count int
}
func getMyQueue() * MyQueue {
	// return new MyQueue
	return &MyQueue {
		nil,
		nil,
		0,
	}
}
func(this MyQueue) size() int {
	return this.count
}
func(this MyQueue) isEmpty() bool {
	return this.count == 0
}
// Add new node of queue
func(this *MyQueue) enqueue(value int) {
	// Create a new node
	var node * QNode = getQNode(value)
	if this.head == nil {
		// Add first element into queue
		this.head = node
	} else {
		// Add node at the end using tail 
		this.tail.next = node
	}
	this.count++
	this.tail = node
}
// Delete a element into queue
func(this *MyQueue) dequeue() int {
	if this.head == nil {
		fmt.Println("Empty Queue")
		return -1
	}
	// Pointer variable which are storing 
	// the address of deleted node
	var temp * QNode = this.head
	// Visit next node 
	this.head = this.head.next
	this.count--
	if this.head == nil {
		// When deleting a last node of linked list
		this.tail = nil
	}
	return temp.data
}
// Get front node
func(this MyQueue) peek() int {
	if this.head == nil {
		fmt.Println("Empty Queue")
		return -1
	}
	return this.head.data
}
func main() {
	var task * MyQueue = getMyQueue()
	// Initially number of element
	fmt.Println("isEmpty : ", task.isEmpty())
	// Add element into queue
	task.enqueue(10)
	task.enqueue(20)
	task.enqueue(30)
	task.enqueue(40)
	task.enqueue(50)
	// Test other function
	fmt.Println("size : ", task.size())
	fmt.Println("peek : ", task.peek())
	fmt.Println("dequeue : ", task.dequeue())
	fmt.Println("size : ", task.size())
	fmt.Println("peek : ", task.peek())
	fmt.Println("isEmpty : ", task.isEmpty())
}

Output

isEmpty :  true
size :  5
peek :  10
dequeue :  10
size :  4
peek :  20
isEmpty :  false


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