-
Notifications
You must be signed in to change notification settings - Fork 138
/
Java program to implement Stack
139 lines (70 loc) · 1.71 KB
/
Java program to implement Stack
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// Stack implementation in Java
class Stack {
// store elements of stack
private int arr[];
// represent top of stack
private int top;
// total capacity of the stack
private int capacity;
// Creating a stack
Stack(int size) {
// initialize the array
// initialize the stack variables
arr = new int[size];
capacity = size;
top = -1;
}
// push elements to the top of stack
public void push(int x) {
if (isFull()) {
System.out.println("Stack OverFlow");
// terminates the program
System.exit(1);
}
// insert element on top of stack
System.out.println("Inserting " + x);
arr[++top] = x;
}
// pop elements from top of stack
public int pop() {
// if stack is empty
// no element to pop
if (isEmpty()) {
System.out.println("STACK EMPTY");
// terminates the program
System.exit(1);
}
// pop element from top of stack
return arr[top--];
}
// return size of the stack
public int getSize() {
return top + 1;
}
// check if the stack is empty
public Boolean isEmpty() {
return top == -1;
}
// check if the stack is full
public Boolean isFull() {
return top == capacity - 1;
}
// display elements of stack
public void printStack() {
for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + ", ");
}
}
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.print("Stack: ");
stack.printStack();
// remove element from stack
stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();
}
}