-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack using Array in Java
More file actions
62 lines (52 loc) · 1.48 KB
/
Stack using Array in Java
File metadata and controls
62 lines (52 loc) · 1.48 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
public class Stack {
private int maxSize;
private int[] stackArray;
private int top;
public Stack(int size) {
this.maxSize = size;
this.stackArray = new int[maxSize];
this.top = -1;
}
public void push(int value) {
if (isFull()) {
System.out.println("Stack is full. Cannot push element.");
return;
}
top++;
stackArray[top] = value;
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty. Cannot pop element.");
return -1;
}
int value = stackArray[top];
top--;
return value;
}
public int peek() {
if (isEmpty()) {
System.out.println("Stack is empty. Cannot peek element.");
return -1;
}
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
System.out.println("Top element after pushing 5 elements: " + stack.peek());
System.out.println("Popped element: " + stack.pop());
System.out.println("Popped element: " + stack.pop());
System.out.println("Top element after popping 2 elements: " + stack.peek());
}
}