-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPushAtIndex.java
More file actions
68 lines (59 loc) · 1.79 KB
/
Copy pathPushAtIndex.java
File metadata and controls
68 lines (59 loc) · 1.79 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
public class PushAtIndex {
static class Stack{
int maxsize;
int stackArray[];
int top;
Stack(int size){
maxsize= size;
stackArray= new int[size];
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 pushAtIndex(int index, int val){
if(index<0 || index>top+1){
System.out.println("Invalid index for insertion");
return;
}
if(top==maxsize-1){
System.out.println("Stack overflow");
return;
}
// Shift elements to the right to make space for the new element
for(int i=top; i>=index; i--){
stackArray[i+1]= stackArray[i];
}
stackArray[index]= val;
top++;
System.out.println(val + " inserted at index " + index);
}
void display(){
if(top==-1){
System.out.println("Empty stack");
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(1);
st.push(2);
st.push(3);
st.push(4);
st.display(); // 1 2 3 4
st.pushAtIndex(2, 98);
st.display(); // 1 2 98 3 4
st.pushAtIndex(3, 16); // Stack overflow
st.pushAtIndex(12, 105); // Invalid index for insertion
}
}