Stack data structure

This is C# example code for a stack data structure. If you are not sure about the stack, i recommend to read: Algorithm and Data Structure tutorial.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
class Program
{

static void Main(string[] args)
{
Stack<int> mystack = new Stack<int>();
mystack.push(100);
mystack.push(101);
mystack.push(102);
int del = mystack.pop();
if (del != 0)
Console.WriteLine("The deleted item:{0}", del);
mystack.showall();
Console.ReadLine();
}

class ListNode<T> //T is the generic type.
{
public ListNode(T elem) { val = elem; prev = next = null; }
public T val; //node data
public ListNode<T> prev;//previous link
public ListNode<T> next;//next link
}

class Stack<T>
{
public Stack() { pfirst = plast = null; }
protected ListNode<T> pfirst;
protected ListNode<T> plast;
public void push(T val)
{
ListNode<T> newnode = new ListNode<T>(val);
//empty list
if (pfirst == null && plast == null)
{
pfirst = newnode;
plast = newnode;
Console.WriteLine("Inserted:{0}", newnode.val);
}
//Insert at the beginning of the list
else
{
ListNode<T> f;
f = pfirst;
pfirst = newnode;
pfirst.next = f;
f.prev = pfirst;
Console.WriteLine("Inserted:{0}", newnode.val);
}

}

public void showall()
{
ListNode<T> t;
if (countitem() > 0)
{
Console.WriteLine("All items in the stack:");
for (t = pfirst; t != null; t = t.next)
{

Console.WriteLine(t.val);
}
}
else Console.WriteLine("No item found!");
}
public int countitem()
{
ListNode<T> i;
int t = 0;
for (i = pfirst; i != null; i = i.next)
{
t = t + 1;
}
return t;
}
public T pop()
{
T delitem=default(T) ;
if (countitem() > 0)
{ //make sure the list is not empty.
ListNode<T> temp;


//delete the first item
temp = pfirst;
delitem = temp.val;
pfirst = pfirst.next;
pfirst.prev = null;
temp = null;
}


else Console.WriteLine("No item found");
return delitem;
}

}
}

}


HTML Comment Box is loading comments...



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.