-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
57 lines (48 loc) · 1.55 KB
/
Copy pathStack.java
File metadata and controls
57 lines (48 loc) · 1.55 KB
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
public class Stack {
int size = 20;
Integer[] stack = new Integer[size];
int top = -1;
public static void main(String[] args){
Stack stack = new Stack();
System.out.println("Pushing 10...");
stack.Push(10);
System.out.println("Pushing 20...");
stack.Push(20);
System.out.println("Peeking top...");
Integer peeked = stack.Peek();
System.out.println("Top element is: " + peeked);
System.out.println("Popping...");
stack.Pop();
System.out.println("Peeking again...");
peeked = stack.Peek();
System.out.println("Top element is now: " + peeked);
System.out.println("Popping again...");
stack.Pop();
System.out.println("Attempting one more pop (should trigger underflow)...");
stack.Pop();
}
private void Push(int data){
if(top >= size - 1){
System.out.println("OverFlow error. You cannot Push into a full stack");
return;
}
top++;
stack[top] = data;
}
private void Pop(){
if(top <= -1){
System.out.println("UnderFlow Error. You cannot Pop from an empty list");
return;
}
System.out.println(stack[top] + " has been removed from the stack");
stack[top] = null;
top--;
}
private Integer Peek(){
if(top <= -1){
System.out.println("Stack is empty");
return null;
}
return stack[top];
}
}