Last active
December 20, 2015 08:19
-
-
Save brandedoutcast/6100056 to your computer and use it in GitHub Desktop.
This is a C# code snippet to create Stack class without using Arrays. Its an integer stack class which can be easily modified to a generic class in order to support multiple data types.
This file contains 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
class Stack | |
{ | |
static int TotalCount; | |
static Element Minimum; | |
static Element Top; | |
public void Push(int Value) | |
{ | |
Element Item; | |
if (TotalCount != 0) | |
{ | |
Item = new Element(Value, Top); | |
if (Minimum.Data > Value) Minimum = Item; | |
} | |
else | |
{ | |
Item = new Element(Value, null); | |
Minimum = Item; | |
} | |
Top = Item; | |
TotalCount++; | |
} | |
public int Pop() | |
{ | |
if (TotalCount == 0) return -1; | |
else | |
{ | |
int Value = Top.Data; | |
if (Top == Minimum && TotalCount != 1) | |
{ | |
Minimum = Top.Previous; | |
ComputeMinimum(Top.Previous); | |
} | |
Top = Top.Previous; | |
TotalCount--; | |
return Value; | |
} | |
} | |
private Element ComputeMinimum(Element CurrentTop) | |
{ | |
if (CurrentTop.Previous != null) | |
{ | |
if (Minimum.Data > CurrentTop.Previous.Data) | |
Minimum = CurrentTop.Previous; | |
return ComputeMinimum(CurrentTop.Previous); | |
} | |
return Minimum; | |
} | |
public int GetMinimum() | |
{ | |
if (TotalCount == 0) return -1; | |
else return Minimum.Data; | |
} | |
public void DisplayAllItems() | |
{ | |
if (TotalCount != 0) | |
{ | |
System.Console.WriteLine("Elements in the stack are :"); | |
PrintItems(Top); | |
System.Console.WriteLine(); | |
} | |
else | |
{ | |
System.Console.WriteLine("The stack is empty"); | |
System.Console.WriteLine(); | |
} | |
} | |
private void PrintItems(Element top) | |
{ | |
if (top.Previous != null) { PrintItems(top.Previous); System.Console.WriteLine(top.Data); } | |
else System.Console.WriteLine(top.Data); | |
} | |
} | |
class Element | |
{ | |
public int Data { get; private set; } | |
public Element Previous { get; private set; } | |
public Element(int Value, Element Top) | |
{ | |
Data = Value; | |
Previous = Top; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment