Sort stack using another stack in typescript

Ts program for Sort stack using another stack. Here problem description and explanation.

// TypeScript program for
// Sort stack using another stack
// Stack Node
class StackNode
{
	public data: number;
	public next: StackNode;
	constructor(data: number, top: StackNode)
	{
		this.data = data;
		this.next = top;
	}
}
class MyStack
{
	public top: StackNode;
	public count: number;
	constructor()
	{
		this.top = null;
		this.count = 0;
	}
	// Returns the number of element in stack
	public number size()
	{
		return this.count;
	}
	public boolean isEmpty()
	{
		if (this.size() > 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	// Add a new element in stack
	public push(data: number)
	{
		// Make a new stack node
		// And set as top
		this.top = new StackNode(data, this.top);
		// Increase node value
		this.count++;
	}
	// Add a top element in stack
	public pop()
	{
		if (this.isEmpty() == false)
		{
			this.top = this.top.next;
			// Reduce size
			this.count--;
		}
	}
	// Used to get top element of stack
	public number peek()
	{
		if (!this.isEmpty())
		{
			return this.top.data;
		}
		else
		{
			return 0;
		}
	}
}
class Test
{
	public MyStack sortStack(s: MyStack)
	{
		// Other auxiliary stack
		var auxiliary = new MyStack();
		while (!s.isEmpty())
		{
			// Get top element
			var temp = s.peek();
			// Delete top element
			s.pop();
			while (auxiliary.isEmpty() == false && auxiliary.peek() < temp)
			{
				// Add element into actual stack
				s.push(auxiliary.peek());
				// Remove element of auxiliary stack
				auxiliary.pop();
			}
			// Add current element
			auxiliary.push(temp);
		}
		// Return sorted stack
		return auxiliary;
	}
	public static main()
	{
      	var task = new Test();
		var s = new MyStack();
		// Add the stack element
		s.push(4);
		s.push(7);
		s.push(9);
		s.push(1);
		s.push(12);
		s.push(3);
		s.push(8);
		s.push(5);
		s.push(6);
		s.push(10);
		/*
		  Created Stack
		  ============
		  10  <- Top
		  6  
		  5  
		  8  
		  3  
		  12 
		  1  
		  9  
		  7  
		  4
		*/
		// Sort operation
		s = task.sortStack(s);
		/*
		  Sort Stack
		  ============
		  1  <- Top
		  3  
		  4  
		  5  
		  6  
		  7  
		  8  
		  9  
		  10  
		  12
		*/
		// Display result
		while (s.isEmpty() == false)
		{
			// Get top element
			console.log(s.peek());
			// Delete top element
			s.pop();
		}
	}
}
Test.main();
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

Output

1
3
4
5
6
7
8
9
10
12



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







© 2022, kalkicode.com, All rights reserved