-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainStack.java
More file actions
85 lines (68 loc) · 1.84 KB
/
MainStack.java
File metadata and controls
85 lines (68 loc) · 1.84 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
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
class Stack {
private int[] array;
private int topPosition;
private int capacity;
Stack(int size) {
array = new int[size];
capacity = size;
topPosition = -1;
}
public void push(int element) {
if (isFull()) {
System.out.println("The Stack is full, element could not be inserted");
} else {
topPosition = topPosition + 1;
array[topPosition] = element;
}
}
public void pop() {
if (isEmpty()) {
System.out.println("The Stack is empty, no element was removed");
} else {
topPosition = topPosition - 1;
}
}
public boolean isEmpty() {
return (this.topPosition == -1);
}
public boolean isFull() {
return (this.topPosition == this.capacity - 1);
}
public int peek() {
return this.array[topPosition];
}
public void printStack() {
if (isEmpty()) {
System.out.println("Stack is Empty");
} else {
for (int i = 0; i <= topPosition; i++) {
System.out.print(this.array[i]);
if (i != topPosition) {
System.out.print("-->");
}
}
System.out.println();
}
}
}
public class MainStack {
public static void main(String[] args) {
Stack s1 = new Stack(10);
s1.printStack();
s1.push(10);
s1.push(20);
s1.push(30);
s1.printStack();
System.out.println(s1.peek());
s1.pop();
s1.printStack();
s1.pop();
s1.printStack();
s1.pop();
s1.printStack();
s1.pop();
s1.printStack();
s1.pop();
s1.printStack();
}
}