-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplement a stack with push and pop operations
82 lines (75 loc) · 2.05 KB
/
implement a stack with push and pop operations
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
Write a Java program to implement a stack with push and pop operations. Find the top element of the stack and check if the stack is empty or not.
///yay
import java.util.Scanner;
public class Stack {
private int[] arr;
private int top;
// Constructor to initialize the stack
public Stack(int size) {
arr = new int[size];
top = -1;
}
// Method to push an element onto the stack
public void push(int num) {
if (top == arr.length - 1) {
System.out.println("Stack is full");
} else {
top++;
arr[top] = num;
}
}
// Method to pop an element from the stack
public int pop() {
if (top == -1) {
System.out.println("Stack Underflow");
return -1;
} else {
int poppedElement = arr[top];
top--;
return poppedElement;
}
}
// Method to get the top element of the stack
public int peek() {
if (top == -1) {
System.out.println("Stack is empty");
return -1;
} else {
return arr[top];
}
}
// Method to check if the stack is empty
public boolean isEmpty() {
return top == -1;
}
public void display() {
if (top == -1) {
System.out.println("Stack is empty");
} else {
System.out.print("Stack elements: ");
for (int i = top; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
System.out.println("Initialize a stack:");
Stack stack = new Stack(5);
System.out.println("Is the stack empty? " + stack.isEmpty());
System.out.println("\nInput some elements on the stack:");
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.display();
System.out.println("\nTop element of the stack: " + stack.peek());
System.out.println("\nRemove two element from the stack:");
stack.pop();
stack.pop();
stack.display();
System.out.println("\nTop element of the stack after popping: " + stack.peek());
System.out.println("\nIs the stack empty? " + stack.isEmpty());
}
}