-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertAtBottom.java
More file actions
64 lines (54 loc) · 1.58 KB
/
Copy pathInsertAtBottom.java
File metadata and controls
64 lines (54 loc) · 1.58 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
public class InsertAtBottom {
static class Stack{
int maxsize;
int stackArray[];
int top;
Stack(int size){
maxsize= size;
stackArray= new int[maxsize];
top= -1;
}
void push(int val){
if(top==maxsize-1){
System.out.println("Stack overflow");
return;
}
stackArray[++top]= val;
System.out.println(val + " pushed into stack");
}
void insertAtBottom(int val){
if(top==maxsize-1){
System.out.print("Stack overflow");
return;
}
// Shift all elements to the right to make space for the new element
for(int i=top; i>=0; i--){
stackArray[top+1]= stackArray[top];
}
stackArray[0]= val;
top++;
System.out.println(val + " pushed at bottom of the stack");
}
void display(){
if(top==-1){
System.out.println("Stack is empty");
return;
}
for(int i=0; i<=top; i++){
System.out.print(stackArray[i] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Stack st= new Stack(5);
st.push(7);
st.push(4);
st.push(9);
st.push(5);
st.display(); // 7 4 9 5
st.insertAtBottom(1);
st.display(); // 1 7 4 9 5
st.insertAtBottom(6); //Stack overflow
}
}