Skip to content

Instantly share code, notes, and snippets.

@dislogical
Created March 13, 2012 01:05
Show Gist options
  • Select an option

  • Save dislogical/2025862 to your computer and use it in GitHub Desktop.

Select an option

Save dislogical/2025862 to your computer and use it in GitHub Desktop.
Stack data structure: FIFO
using System;
namespace YOUR_PROJECT_NAMESPACE
{
/// <summary>
/// A node based implementation of a stack
/// Adapted from prior GSD2 material with many other authors
/// A lot of this code was written by Professor Schwartz</summary>
/// <typeparam name="T">
/// The data type the NodeStack holds</typeparam>
/// <author>Colden Cullen</author>
class Stack<T> : List<T>
{
#region Fields
/// <summary>
/// Max size for the stack</summary>
int maxSize;
#endregion
#region Constructors
/// <summary>
/// Default Constructor</summary>
public Stack() : this( 0 ) { }
/// <summary>
/// Constructor for max size</summary>
/// <param name="maxSize">
/// Biggest stack can be</param>
public Stack( int maxSize )
{
this.maxSize = maxSize;
head = null;
}
#endregion
#region Add Remove
/// <summary>
/// Adds an element to the stack</summary>
/// <param name="data">
/// The element to add</param>
public override void Add( T data )
{
Node<T> add = new Node<T>( data, count );
add.Next = head;
head = add;
if( maxSize != 0 )
if( count == maxSize )
{
this.RemoveAt( maxSize - 1 );
count--;
}
count++;
}
/// <summary>
/// Quietly removes the top element on the stack</summary>
/// <exception>
/// Throws an UnderflowException if the stack is empty</exception>
public void Pop()
{
if( head != null )
{
head = head.Next;
count--;
}
else throw new Exception( "Stack is empty!" );
}
/// <summary>
/// Returns the top element on the stack without removing it</summary>
/// <returns>
/// The top element</returns>
/// <exception>
/// Throws an UnderflowException if the stack is empty</exception>
public T Peek()
{
if( head != null )
{
return head.Data;
}
else throw new Exception( "Stack is empty!" );
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment