implement queue using linked list in scala

Scala program for implement queue using linked list. Here problem description and explanation.

/*
  Scala Program for
  Implement queue using linked list
*/
// Create Q node
class QNode(var data: Int,
	var next: QNode)
{
	def this(value: Int)
	{
		this(value, null);
	}
}
class MyQueue(var head: QNode,
	var tail: QNode,
		var count: Int)
{
	def this()
	{
		this(null, null, 0);
	}
	def size(): Int = {
		return this.count;
	}
	def isEmpty(): Boolean = {
		return this.count == 0;
	}
	// Add new node of queue
	def enqueue(value: Int): Unit = {
		// Create a new node
		var node: QNode = new QNode(value);
		if (this.head == null)
		{
			// Add first element into queue
			this.head = node;
		}
		else
		{
			// Add node at the end using tail 
			this.tail.next = node;
		}
		this.count += 1;
		this.tail = node;
	}
	// Delete a element into queue
	def dequeue(): Int = {
		if (this.head == null)
		{
			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 = head.next;
		this.count -= 1;
		if (this.head == null)
		{
			// When deleting a last node of linked list
			this.tail = null;
		}
		return temp.data;
	}
	// Get front node
	def peek(): Int = {
		if (this.head == null)
		{
			println("Empty Queue");
			return -1;
		}
		return this.head.data;
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: MyQueue = new MyQueue();
		// Initially number of element
		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
		println("size : " + task.size());
		println("peek : " + task.peek());
		println("dequeue : " + task.dequeue());
		println("size : " + task.size());
		println("peek : " + task.peek());
		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