Use the operations push, pop, peek, and empty to write operations that do each o
ID: 3561927 • Letter: U
Question
Use the operations push, pop, peek, and empty to write operations that do each of the following in java:
1. set i to the second element from the top of the stack; leaving the stack without its top two elements.
2. set i to the second element from the top of the stack; leaving the stack unchanged.
3. Given an integer n, set i to the nth element from the top of the stack; leaving stack without its top n elements.
4. Given an integer n, set i to the nth element from the top of the stack; leaving stack unchanged.
5. Set i to the bottom element of the stack; leaving the stack empty.
6. Set i to the bottom element of the stack; leaving the stack unchanged (Hint: use another, auxiliary stack)
7. Set i to third element from the bottom of the stack.
Explanation / Answer
1. If(s.size() != 0) { i = s.pop();}
If(s.size() != 0) { i = s.pop();}
2.If(s.size() != 0) {temp1 = s.pop()}
If(s.size() != 0) {temp2 = s.pop()}
i = temp2
s.push(temp2)
s.push(temp1)
3. for(int k = 0; k < n; k++){
If(s.size() != 0){
i = s.pop()
}
4. Create temporary array to store popped elements : temp[n]
for(int k = 0; k < n; k++){
If(s.size() != 0){
temp[i] = s.pop()
}
}
i = temp[n]
for(int k = 0; k < n; k++){
s.push(temp[i])
}
5. for(i = 0 ; i < s.size() ; i++){
i = s.pop()
}
6. Create temporary stack to store popped elements : st2[SIZE]
for(int k = 0; k < SIZE; k++){
If(s.size() != 0){
x = s.pop();
st2.push(x);
}
}
i = x
for(int k = 0; k < SIZE; k++){
s.push(st2[i])
}
7. for(int j = SIZE; j >3; j--){
i = s.pop()
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.