implement queue using linked list in typescript

Ts program for implement queue using linked list. Here problem description and other solutions.

/*
  TypeScript Program for
  Implement queue using linked list
*/
// Create Q node
class QNode
{
	public data: number;
	public next: QNode;
	constructor(value: number)
	{
		this.data = value;
		this.next = null;
	}
}
class MyQueue
{
	public head: QNode;
	public tail: QNode;
	public count: number;
	constructor()
	{
		this.head = null;
		this.tail = null;
		this.count = 0;
	}
	public number size()
	{
		return this.count;
	}
	public boolean isEmpty()
	{
		return this.count == 0;
	}
	// Add new node of queue
	public enqueue(value: number)
	{
		// Create a new node
		var node = 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++;
		this.tail = node;
	}
	// Delete a element into queue
	public number dequeue()
	{
		if (this.head == null)
		{
			console.log("Empty Queue");
			return -1;
		}
		// Pointer variable which are storing 
		// the address of deleted node
		var temp = this.head;
		// Visit next node 
		this.head = this.head.next;
		this.count--;
		if (this.head == null)
		{
			// When deleting a last node of linked list
			this.tail = null;
		}
		return temp.data;
	}
	// Get front node
	public number peek()
	{
		if (this.head == null)
		{
			console.log("Empty Queue");
			return -1;
		}
		return this.head.data;
	}
	public static main(args: string[])
	{
		var task = new MyQueue();
		// Initially number of element
		console.log("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
		console.log("size : " + task.size());
		console.log("peek : " + task.peek());
		console.log("dequeue : " + task.dequeue());
		console.log("size : " + task.size());
		console.log("peek : " + task.peek());
		console.log("isEmpty : " + task.isEmpty());
	}
}
MyQueue.main([]);
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

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