Topic: | Data Structures (Stacks, Queues) |
---|---|
Author: | Peter Bui <pbui@cse.nd.edu> |
Date: | September 09, 2009 |
Abstract data type that is "last in first out" (LIFO):
[3] <- top of the stack [2] [1] [0] <- bottom of the stack
Push: Add item to the top of the stack:
stack.push(value);
Pop: Remove item from the top of the stack:
stack.pop();
Top: Access the item at the top of the stack:
stack.top();
stack<int> s;
s.push(0);
s.push(1);
s.push(2);
while (!s.empty()) {
cout << s.top() endl;
s.pop();
}
Abstract data type that is "first in first out" (FIFO):
back -> [3 2 1 0] <- front
Push Back: add item to queue:
queue.push_back(0); // enqueue
Pop Front: remove item from queue:
queue.pop_front(); // dequeue
Front, Back: access items at the front and back of queue:
queue.front(); queue.back();
queue<int> q;
q.push_back(0);
q.push_back(1);
q.push_back(2);
while (!q.empty()) {
cout << q.front() endl;
q.pop_front();
}
Problem:
Describe a stack data structure that supports a "find minimum" operation in addition to "push" and "pop":
s.push(0); s.push(1); cout << s.find_minimum() << endl;
Trick: have all operations be O(1).
Use two stacks: sall (contains all elements), smin (stack of minima).
Problem:
Describe how you would construct a queue using one or more stacks. Write the enqueue and dequeue operations.
Use two stacks: incoming and the other outgoing.
void enqueue(int v) {
while (!outgoing.empty())
incoming.push(outgoing.top()); outgoing.pop();
incoming.push(v)
}
int dequeue() {
int result;
while (!incoming.empty())
outgoing.push(incoming.top()); incoming.pop();
result = outgoing.top(); outgoing.pop();
return (result);
}