implement queue using linked list in swift

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

import Foundation
/*
  Swift 4 Program for
  Implement queue using linked list
*/
// Create Q node
class QNode
{
	var data: Int;
	var next: QNode? ;
	init(_ value: Int)
	{
		self.data = value;
		self.next = nil;
	}
}
class MyQueue
{
	var head: QNode? ;
	var tail: QNode? ;
	var count: Int;
	init()
	{
		self.head = nil;
		self.tail = nil;
		self.count = 0;
	}
	func size() -> Int
	{
		return self.count;
	}
	func isEmpty() -> Bool
	{
		return self.count == 0;
	}
	// Add new node of queue
	func enqueue(_ value: Int)
	{
		// Create a new node
		let node: QNode? = QNode(value);
		if (self.head == nil)
		{
			// Add first element into queue
			self.head = node;
		}
		else
		{
			// Add node at the end using tail 
			self.tail!.next = node;
		}
		self.count += 1;
		self.tail = node;
	}
	// Delete a element into queue
	func dequeue() -> Int
	{
		if (self.head == nil)
		{
			print("Empty Queue");
			return -1;
		}
		// Pointer variable which are storing 
		// the address of deleted node
		let temp: QNode? = self.head;
		// Visit next node 
		self.head = self.head!.next;
		self.count -= 1;
		if (self.head == nil)
		{
			// When deleting a last node of linked list
			self.tail = nil;
		}
		return temp!.data;
	}
	// Get front node
	func peek() -> Int
	{
		if (self.head == nil)
		{
			print("Empty Queue");
			return -1;
		}
		return self.head!.data;
	}
	static func main(_ args: [String])
	{
		let task: MyQueue? = MyQueue();
		// Initially number of element
		print("isEmpty : "
			+ String(task!.isEmpty()));
		// Add element into queue
		task!.enqueue(10);
		task!.enqueue(20);
		task!.enqueue(30);
		task!.enqueue(40);
		task!.enqueue(50);
		// Test other function
		print("size : ",task!.size());
		print("peek : ",task!.peek());
		print("dequeue : ",task!.dequeue());
		print("size : ",task!.size());
		print("peek : ",task!.peek());
		print("isEmpty : ",task!.isEmpty());
	}
}
MyQueue.main([String]());

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