CSE 40872 Lecture 006

Topic:Data Structures (Stacks, Queues)
Author: Peter Bui <pbui@cse.nd.edu>
Date: September 09, 2009

Stacks

Abstract data type that is "last in first out" (LIFO):

[3] <- top of the stack
[2]
[1]
[0] <- bottom of the stack

Stack Operations

  1. Push: Add item to the top of the stack:

    stack.push(value);
    
  2. Pop: Remove item from the top of the stack:

    stack.pop();
    
  3. Top: Access the item at the top of the stack:

    stack.top();
    

Stack Example

stack<int> s;

s.push(0);
s.push(1);
s.push(2);

while (!s.empty()) {
    cout << s.top() endl;
    s.pop();
}

Queues

Abstract data type that is "first in first out" (FIFO):

back -> [3 2 1 0] <- front

Queue Operations

Queue Example

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();
}

Minimum Stack

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).

Solution

Use two stacks: sall (contains all elements), smin (stack of minima).

Queues Using Stacks

Problem:

Describe how you would construct a queue using one or more stacks. Write the enqueue and dequeue operations.

Solution

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);
}