-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.cs
92 lines (84 loc) · 2.22 KB
/
Stack.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication18
{
class Stack
{
// stack fields...
int top;
public int[] arr;
// stack constructor
public Stack(int stackLength) {
this.top = -1;
this.arr = new int[stackLength];
}
// push method
public void push(int item) {
if (this.isFull())
Console.WriteLine("Stack Overflow");
else {
top++;
arr[top] = item;
}
}
// pop method
public void pop() {
if (this.isEmpty())
Console.WriteLine("no items to pop. Stack Underflow!");
else {
this.arr[top] = 0;
this.top--;
}
}
// isEmpty method
public bool isEmpty() {
if (this.top == -1)
return true;
else
return false;
}
// isFull method
public bool isFull() {
if (this.top == this.arr.Length - 1)
return true;
else
return false;
}
// peek method
public void peek() {
if (!this.isEmpty())
Console.WriteLine("retrieved element: " + this.arr[this.top]);
else {
Console.WriteLine("Stack Underflow...");
}
}
// display method
public void display() {
for (int i = this.arr.Length - 1; i >= 0; i--)
{
Console.WriteLine(" ___");
Console.WriteLine(" | " + this.arr[i] + " | ");
}
Console.WriteLine("________________________________");
}
}
class Program
{
static void Main(string[] args)
{
Stack myStack = new Stack(3);
myStack.display();
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.display();
myStack.pop();
myStack.display();
myStack.pop();
myStack.display();
}
}
}