Last active
May 13, 2019 23:07
-
-
Save Youngchangoon/3703b2ee9d322e127aab34a2771085ab to your computer and use it in GitHub Desktop.
Stack ( array )
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
using System; | |
namespace ConsoleApp1 | |
{ | |
public class Program | |
{ | |
private static StackArray<int> stackArray; | |
static void Main(string[] args) | |
{ | |
stackArray = new StackArray<int>(2); | |
// Push | |
Console.WriteLine("Try Push 100"); stackArray.Push(100); | |
Console.WriteLine("Try Push 200"); stackArray.Push(200); | |
Console.WriteLine("Try Push 300"); stackArray.Push(300); | |
// Top | |
Console.WriteLine("TOP is: " + stackArray.Top()); | |
// Pop | |
Console.WriteLine("Pop Data is: " + stackArray.Pop()); | |
// IsEmpty | |
Console.WriteLine("IsEmpty: " + stackArray.IsEmpty()); | |
stackArray.PrintNode(); | |
} | |
} | |
public class StackArray<T> | |
{ | |
private T[] array; | |
private int topIdx; | |
public StackArray(int capacity) | |
{ | |
array = new T[capacity]; | |
topIdx = -1; | |
} | |
public void Push(T data) | |
{ | |
if (topIdx == array.Length - 1) | |
{ | |
Console.WriteLine("Push Fail.. data: " + data); | |
return; | |
} | |
array[++topIdx] = data; | |
} | |
public T Pop() | |
{ | |
if (IsEmpty()) | |
throw new Exception("Empty Stack.."); | |
var data = array[topIdx]; | |
array[topIdx--] = default(T); | |
return data; | |
} | |
public T Top() | |
{ | |
if (IsEmpty()) | |
throw new Exception("Empty Stack.."); | |
return array[topIdx]; | |
} | |
public bool IsEmpty() | |
{ | |
return topIdx < 0; | |
} | |
public void PrintNode() | |
{ | |
if (IsEmpty()) | |
{ | |
Console.WriteLine("Empty Stack"); | |
return; | |
} | |
Console.WriteLine("---- TOP ----"); | |
for(var i = topIdx; i >= 0; --i) | |
{ | |
Console.WriteLine(array[i]); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment