-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStacks_using_Array.java
More file actions
90 lines (75 loc) · 1.68 KB
/
Stacks_using_Array.java
File metadata and controls
90 lines (75 loc) · 1.68 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
86
87
88
89
90
class MyStack {
// array to store elements
private int arr[];
//max size of stack;
private int capacity;
// index of top element
private int top;
//constructor
public MyStack(int cap) {
capacity = cap;
arr = new int[capacity];
top = -1;
}
//push operation
public void push(int val) {
if(top == capacity-1) {
System.out.println("Stack overflow!!");
return;
}
arr[++top] = val;
System.out.println(val+" pushed to stack");
}
//pop operation
public int pop() {
if(top == -1) {
System.out.println("Stack Underflow");
return -1;
}
int popped = arr[top--];
System.out.println(popped+ " popped from stack");
return popped;
}
//peek(top element)
public int peek() {
if(top == -1) {
System.out.println("Stack is empty");
return -1;
}
return arr[top];
}
// isEmpty
public boolean isEmpty() {
return top == -1;
}
// isFull
public boolean isFull() {
return top == capacity-1;
}
//Display stack elements
public void display() {
if(isEmpty()) {
System.out.println("Stack is empty: ");
return;
}
System.out.println("Stack elements: ");
for(int i = 0; i<=top;i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
}
}
public class Stacks_using_Array {
public static void main(String[] args) {
MyStack s = new MyStack(5);
s.push(10);
s.push(20);
s.push(5);
s.display();
System.out.println("Top element: "+s.peek());
s.pop();
s.display();
System.out.println("Is stack empty?" + s.isEmpty());
System.out.println("Is stack is full?"+s.isFull());
}
}