implement stack using linked list in swift

Swift program for implement stack using linked list. Here more information.

import Foundation
// Swift 4 program for
// Implementation stack using linked list

// Stack Node
class StackNode
{
	var data: Int;
	var next: StackNode? ;
	init(_ data: Int, _ top: StackNode? )
	{
		self.data = data;
		self.next = top;
	}
}
class MyStack
{
	var top: StackNode? ;
	var count: Int;
	init()
	{
		self.top = nil;
		self.count = 0;
	}
	// Returns the number of element in stack
	func size() -> Int
	{
		return self.count;
	}
	func isEmpty() -> Bool
	{
		if (self.size() > 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	// Add a new element in stack
	func push(_ data: Int)
	{
		// Make a new stack node
		// And set as top
		self.top = StackNode(data, self.top);
		// Increase node value
		self.count += 1;
	}
	// Add a top element in stack
	func pop() -> Int
	{
		var temp: Int = 0;
		if (self.isEmpty() == false)
		{
			// Get remove top value
			temp = self.top!.data;
			self.top = self.top!.next;
			// Reduce size
			self.count -= 1;
		}
		return temp;
	}
	// Used to get top element of stack
	func peek() -> Int
	{
		if (!self.isEmpty())
		{
			return self.top!.data;
		}
		else
		{
			return 0;
		}
	}
}
class Test
{
	static func main()
	{
		// Create new stack 
		let s: MyStack = MyStack();
		print("\n Is empty : "
			+ String(s.isEmpty()));
		// Add element
		s.push(15);
		s.push(14);
		s.push(31);
		s.push(21);
		s.push(10);
		print("\n Top  : "
			+ String(s.peek()));
		print(" Size : "
			+ String(s.size()));
		print("\n Is empty : "
			+ String(s.isEmpty()));
		// Delete Stack Element
		var data: Int = s.pop();
		print("\n Pop element "
			+ String(data));
		print(" Size : "
			+ String(s.size()));
		data = s.pop();
		print("\n Pop element "
			+ String(data));
		print(" Size : "
			+ String(s.size()));
	}
}
Test.main();

Output

 Is empty : true

 Top  : 10
 Size : 5

 Is empty : false

 Pop element 10
 Size : 4

 Pop element 21
 Size : 3


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