implement stack using linked list in scala

Scala program for implement stack using linked list. Here problem description and other solutions.

// Scala program for
// Implementation stack using linked list
// Stack Node
class StackNode(var data: Int,
	var next: StackNode);

class MyStack(var top: StackNode,
	var count: Int)
{
	def this()
	{
		this(null, 0);
	}
	// Returns the number of element in stack
	def size(): Int = {
		return count;
	}
	def isEmpty(): Boolean = {
		if (this.size() > 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	// Add a new element in stack
	def push(data: Int): Unit = {
		// Make a new stack node
		// And set as top
		this.top = new StackNode(data, this.top);
		// Increase node value
		this.count += 1;
	}
	// Add a top element in stack
	def pop(): Int = {
		var temp: Int = 0;
		if (this.isEmpty() == false)
		{
			// Get remove top value
			temp = this.top.data;
			this.top = this.top.next;
			// Reduce size
			this.count -= 1;
		}
		return temp;
	}
	// Used to get top element of stack
	def peek(): Int = {
		if (!this.isEmpty())
		{
			return top.data;
		}
		else
		{
			return 0;
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		// Create new stack 
		var s: MyStack = new MyStack();
		println("\n Is empty : " + s.isEmpty());
		// Add element
		s.push(15);
		s.push(14);
		s.push(31);
		s.push(21);
		s.push(10);
		println("\n Top  : " + s.peek());
		println(" Size : " + s.size());
		println("\n Is empty : " + s.isEmpty());
		// Delete Stack Element
		var data: Int = s.pop();
		println("\n Pop element " + data);
		println(" Size : " + s.size());
		data = s.pop();
		println("\n Pop element " + data);
		println(" Size : " + s.size());
	}
}

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