implement stack using linked list in c#

Csharp program for implement stack using linked list. Here problem description and explanation.

// Include namespace system
using System;
// Csharp program for
// Implementation stack using linked list

// Stack Node
public class StackNode
{
	public int data;
	public StackNode next;
	public StackNode(int data, StackNode top)
	{
		this.data = data;
		this.next = top;
	}
}
public class MyStack
{
	public StackNode top;
	public int count;
	public MyStack()
	{
		this.top = null;
		this.count = 0;
	}
	// Returns the number of element in stack
	public int size()
	{
		return this.count;
	}
	public bool isEmpty()
	{
		if (this.size() > 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	// Add a new element in stack
	public void push(int data)
	{
		// 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 int pop()
	{
		var temp = 0;
		if (this.isEmpty() == false)
		{
			// Get remove top value
			temp = this.top.data;
			this.top = this.top.next;
			// Reduce size
			this.count--;
		}
		return temp;
	}
	// Used to get top element of stack
	public int peek()
	{
		if (!this.isEmpty())
		{
			return this.top.data;
		}
		else
		{
			return 0;
		}
	}
}
public class Test
{
	public static void Main(String[] args)
	{
		// Create new stack 
		var s = new MyStack();
		Console.WriteLine("\n Is empty : " + s.isEmpty());
		// Add element
		s.push(15);
		s.push(14);
		s.push(31);
		s.push(21);
		s.push(10);
		Console.WriteLine("\n Top  : " + s.peek());
		Console.WriteLine(" Size : " + s.size());
		Console.WriteLine("\n Is empty : " + s.isEmpty());
		// Delete Stack Element
		var data = s.pop();
		Console.WriteLine("\n Pop element " + data);
		Console.WriteLine(" Size : " + s.size());
		data = s.pop();
		Console.WriteLine("\n Pop element " + data.ToString());
		Console.WriteLine(" Size : " + s.size().ToString());
	}
}

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