Skip to content

Instantly share code, notes, and snippets.

@serkansendur
Created May 27, 2013 20:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serkansendur/5659029 to your computer and use it in GitHub Desktop.
Save serkansendur/5659029 to your computer and use it in GitHub Desktop.
c# custom stack implementation. There is already a Stack type in .NET library. Mine is for training purposes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
public class linkedNode<T>
{
public linkedNode<T> next;
public T Data;
public linkedNode(T Data)
{
this.Data = Data;
}
}
public class customStack<T>
{
public void Traverse()
{
linkedNode<T> cursor = head;
while (cursor != null)
{
Console.WriteLine(cursor.Data);
cursor = cursor.next;
}
}
linkedNode<T> head;
linkedNode<T> tail;
// returns the head without removing it
public linkedNode<T> Peek()
{
if (head == null)
throw new Exception("the stack is empty");
return head;
}
// returns the head and removes it
public linkedNode<T> Pop()
{
if (head == null)
throw new Exception("the stack is empty");
linkedNode<T> node = new linkedNode<T>(head.Data);
head = head.next;
return node;
}
public void Push(linkedNode<T> node)
{
if (head != null)
node.next = head;
else
{
node.next = null;
tail = node;
}
head = node;
}
}
static void Main(string[] args)
{
customStack<string> stack = new customStack<string>();
stack.Push(new linkedNode<string>("first"));
stack.Push(new linkedNode<string>("second"));
stack.Push(new linkedNode<string>("third"));
stack.Traverse();
Console.WriteLine("now try to peek");
Console.WriteLine(stack.Peek().Data);
Console.WriteLine("traverse again");
stack.Traverse();
Console.WriteLine("now try to pop");
Console.WriteLine(stack.Pop().Data);
Console.WriteLine("traverse again");
stack.Traverse();
Console.WriteLine("pop two more and traverse again");
stack.Pop(); stack.Pop(); stack.Traverse();
Console.WriteLine("push the items back and traverse again");
stack.Push(new linkedNode<string>("first"));
stack.Push(new linkedNode<string>("second"));
stack.Push(new linkedNode<string>("third"));
stack.Traverse();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment