using System;
namespace Stack_Linked_List_Implementation
{
class Stack
{
public class Node
{
public object item;
public Node next;
public Node() {
}
public Node(object item) {
this.item = item;
}
}
private int length;
private Node top;
public Stack()
{
length = 0;
top = null;
}
public int Length
{
get { return length; }
}
public bool isEmpty()
{
return top == null;
}
public void push(Object item)
{
length++;
top = new Node()
{
next = top,
item = item
};
}
public Object pop()
{
Object item = "";
if (!isEmpty())
{
item = top.item;
top = top.next;
length--;
}
else
{
Console.WriteLine("Error! Stack Underflow");
}
return item;
}
public Object peek()
{
Object item = "";
if (!isEmpty())
{
item = top.item;
}
else
{
Console.WriteLine("Error! Stack Underflow");
}
return item;
}
}
}
-----------------------------------------------------------------------------------------------------------------------
Driver Program Using Stack Class
using System;
namespace Stack_Linked_List_Implementation
{
class Program
{
static void Main(string[] args)
{
Stack stack = new Stack();
stack.push("Apple");
stack.push("Banana");
stack.push("Guava");
Console.WriteLine(stack.pop());
Console.WriteLine(stack.peek());
stack.push("Grape");
stack.push("Orange");
stack.push("Lemon");
Console.WriteLine(stack.pop());
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
}
No comments:
Post a Comment