Created
March 13, 2017 14:09
-
-
Save LindaLawton/d80fad96dd60741e87e225a652c68e70 to your computer and use it in GitHub Desktop.
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 CsharpCodeExamples | |
{ | |
class Program | |
{ | |
public class SimpleStack<T> | |
{ | |
int top; | |
private T[] data; | |
public SimpleStack(int bufferLength) | |
{ | |
data = new T[bufferLength]; | |
} | |
public void Push(T value) | |
{ | |
if (top == data.Length - 1) throw new StackOverflowException(); | |
// Stacks are constant time becouse we always directly accessing "top nr" item in the data array. | |
// We dont have to look at any other item in the array we know exactly which number item we want | |
data[top++] = value; | |
} | |
public T Pop() | |
{ | |
if (top == 0) | |
return default(T); | |
// Stacks are constant time becouse we always directly accessing "top nr" item in the data array. | |
// We dont have to look at any other item in the array we know exactly which number item we want | |
return data[--top]; | |
} | |
} | |
static void Main(string[] args) | |
{ | |
// Stacks are known as First in last out data structures. | |
// Consider a stack of plates on a shelf. | |
// After you wash and dry your dishes you place (pop) each plate onto the stack. | |
// When it is time to eat again you take the plate on the top of the stack (pop) to use first. | |
// Pushing and poping plates on and off the stack are constant time operations. It doesnt matter | |
// how many plates are on the stack it will always take the same amount of time to push or | |
// pop a new plate on or off of the stack | |
//Initialze the stack with a max of 5 items on it. | |
var mystack = new SimpleStack<int?>(5); | |
mystack.Push(1); | |
mystack.Push(2); | |
mystack.Push(3); | |
Console.WriteLine("Poped: " + mystack.Pop()); // should be three | |
Console.WriteLine("Poped: " + mystack.Pop()); // Should be two | |
Console.WriteLine("Poped: " + mystack.Pop()); // should be one | |
Console.WriteLine("Poped: " + mystack.Pop()); // Null as there are no more items on the stack | |
Console.ReadLine(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment