Created
March 13, 2012 01:05
-
-
Save dislogical/2025862 to your computer and use it in GitHub Desktop.
Stack data structure: FIFO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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