#1 - Queues a.i)Trace the following function, at the given snapshots, with the q
ID: 3739251 • Letter: #
Question
#1 - Queues a.i)Trace the following function, at the given snapshots, with the queue (5, 7, 14, 4, 7): void mystery(queueType<int>& q) { stackType<int> s;
while(!q.isEmpty()) { s.push(q.front()); q.dequeue(); }
while(!s.isEmpty()) { q.enqueue(2 * s.top()); s.pop(); }
}
Trace:
Start:
q: (5, 7, 14, 4, 7) s: ()
Third iteration of first loop:
End of first loop:
Third iteration of the second loop:
End of second loop:
a.ii) What does the function do? (1-2 sentences)
b) It is common to think of a real-world Queue as a line of people waiting in a line. (In fact, queue is the British word for a line as we know it in America.) Write two more real-life examples that follow the First-In-First-Out order. Use these to explain the concept of a queue. (~2 sentences each example)
c) The STL queue is considered an ”adapter”. What does that mean generally? What does it mean in the context of a queue? (1-2 sentences each question)
Explanation / Answer
Trace the following function, at the given snapshots, with the queue (5, 7, 14, 4, 7): void mystery(queueType<int>& q) { stackType<int> s;
while(!q.isEmpty()) { s.push(q.front()); q.dequeue(); }
while(!s.isEmpty()) { q.enqueue(2 * s.top()); s.pop(); }
}
Trace:
Start:
q: (5, 7, 14, 4, 7) s: ()
Third iteration of first loop:
q: (4, 7) s: (14, 7, 5)
End of first loop:
Third iteration of the second loop:
q: (14, 8, 28) s: (7, 5)
End of second loop:
a.ii) What does the function do? (1-2 sentences)
in first while loop, we are removing elements from Queue and pusing into
stack. In second while loop, we are poping elements from stack and pusing
twice of popped number in queue
So, basically we are reversing and multiplying Queue elements by 2
b) It is common to think of a real-world Queue as a line of people waiting in a line. (In fact, queue is the British word for a line as we know it in America.) Write two more real-life examples that follow the First-In-First-Out order. Use these to explain the concept of a queue. (~2 sentences each example)
Ans:
1) When a resource is shared among multiple consumers. Examples include CPU scheduling, Disk Scheduling.
2) When data is transferred asynchronously (data not necessarily received at same rate as sent) between two processes. Examples include IO Buffers, pipes, file IO, etc.
c) The STL queue is considered an ”adapter”. What does that mean generally? What does it mean in the context of a queue? (1-2 sentences each question)
Ans: Adapters are data types from STL that adapt a container to provide specific interface. So, Queue interface provides all kind of functionality
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.