-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathStack.java
76 lines (56 loc) · 1.47 KB
/
Stack.java
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
import java.util.Arrays;
public class Stack
{
int top = -1;
int maxSize = 0;
Integer[] array;
public Stack(int size) {
this.maxSize = size;
this.array = new Integer[this.maxSize];
}
public void push(int value) {
if (this.top == this.maxSize - 1) {
System.out.println("Stack is full.");
return;
}
this.array[++top] = value;
System.out.println(Arrays.toString(array));
System.out.println("New top : " + this.top);
}
public void pop() {
if (this.top == -1) {
System.out.println("Stack is empty.");
return;
}
this.array[this.top--] = null;
System.out.println(Arrays.toString(array));
System.out.println("New top : " + this.top);
}
public void peek() {
if (this.top == -1) {
System.out.println("Stack is empty.");
return;
}
System.out.println("Top element : " + this.array[this.top]);
}
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.peek();
stack.push(2);
stack.push(3);
stack.peek();
stack.pop();
stack.push(5);
stack.push(6);
stack.push(7);
stack.push(8);
stack.push(9);
stack.peek();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
}
}