Suppose execute the following stack operations on we a stack of ints. push(1); p
ID: 3706664 • Letter: S
Question
Suppose execute the following stack operations on we a stack of ints. push(1); push(4); push(3); pop() push(5); push(18) pop(); push(7); pop(); pop(); Draw the final state of the stack, and for each pop() operation, write next to it the value that will be popped off the stack. Suppose we have an array-based queue What will the final state of the array look like? (circular buffer) of size 6: int data[6]: 1 12131 4 15 int front8, back e; void enqueue(int x) data[back] x; backs (back + 1) % 6; void dequeue) f , front : (front + 1) 1.6; and we perform the following series of queue operations: enqueue(1); enqueue(4); enqueue(2); enqueue(7); dequeue); dequeue); enqueue(5); dequeue() enqueue(6); dequeue) enqueue(3);Explanation / Answer
Push(1)->pushes 1 to stack now stack will be
1
Push(4) pushes 4 to stack now stack will be
4
1
Push(3) pushes 3 to stack now stack will be
3
4
1
Pop()-> since stack follows lifo 3 will be popped form stack
4
1
Popped value is 3
Push(5)->pushes 5 ro stack
5
4
1
Push(10)->pushes 10 to stack
10
5
4
1
Pop()->pops 10 from stack
5
4
1
Popped value is 10
Push(7) pushes 7 to stack and stack will be as follows
7
5
4
1
Pop() deletes 7 from stack and stack will be
5
4
1
Pop() deletes 5 from stack and stack will be
4
1
Finally stack will be left with elements 1 and 4 after 6 push and 4 pop operations
Queue:
0
1
2
3
4
5
1
1
4
1
4
2
1
4
2
7
4
2
7
2
7
2
7
5
7
5
7
5
6
5
6
3
5
6
Since it is an circular based array even though we reach the end of array and slot 0 Is free we have inserted 3 at position 0 for enqueue(3) as per above given code
Explanation:
Initially front and rear are at position 0
Enqueue(1)
As per code inserts 1 at position pointed by rear that is at position 0 and increments the rear as (rear+1)%6 that is (0+1)%6 that is 1 now rear is at 1
Enqueue(4) inserts 4 at index 1 and rear is 2
Enqueue(2) inserts at index 2 and rear is 3
Enqueue(7) inserts at index 3 and rear is 4
Dequeue() deletes 1 from queue since queue follows fifo scheme and increments front as (front+1)%6 that is (0+1)%6 now front is at position 1
Dequeue() deletes 4 from queue and front is at index 2
Enqueue(5) inserts 5 into queue and rear is now at 5
Dequque() delets 2 from queue and now front is a position 3
Enqueu(6) inserts 6 at position 5 and now rear will be (5+1)%6 is 0 since it is circular array we can insert next elements at next available free slots
Dequque() deletes 7 from queue and front will be 4
Enqueue(3) inserts 3 at position 0 and now rear will be 1
1