CPSC 221

Stacks

Today

Announcements

  • PA1 is due tonight, 11:59 pm
  • Examlet 3 runs Thursday to Sunday — book your seat on PrairieTest
  • PEX3 is posted


Where we’re going

  • Stacks
  • The Stack ADT
  • Two implementations
  • The Witch’s Potion Pantry

Stacks

Abstract Data Type:

Stack ADT:

template<class LIT>
class Stack {
public:
    Stack();  // ~Stack, cctor, op=?
    bool empty() const;
    void push(const LIT & e);
    LIT pop();
private:

    //  ?

};
push(3)
push(8)
push(4)
pop()
pop()
push(6)
pop()
push(2)
pop()
pop()

Push 1, 2, 3 in order, with interleaved pops. What output is impossible?

Stack linked memory implementation:

template<class LIT>
class Stack {
public:
    Stack();  // ~Stack, cctor, op=?
    bool empty() const;
    void push(const LIT & e);
    LIT pop();
private:
    struct Node {
        LIT data;
        Node * next;
    };
    Node * top;
    int size;
};
top 3 6 4
template<class LIT>
LIT Stack<LIT>::pop() {




}
template<class LIT>
void Stack<LIT>::push(LIT d) {
    Node * newN = new Node(d);
    newN->next = top;
    top = newN;
    size++;
}

Stack array based implementation:

template<class LIT>
class Stack {
public:
    Stack();  // ~Stack, cctor, op=?
    bool empty() const;
    void push(const LIT & e);
    LIT pop();
private:
    vector<LIT> items;
};
3 6 8 _______ of stack items[_______]
template<class LIT>
LIT Stack<LIT>::pop() {
    LIT retval = items[_____];
    items.pop_back();
    return retval;
}
template<class LIT>
void Stack<LIT>::push(LIT d) {

    items.push_back(d);

}

Get ready

Open PrairieLearn now: Class Activities → The Witch’s Potion Pantry

Click Open workspace — it takes a minute to start, so let it load while you watch the story.

Your Turn

Every one of you has your own pantry and your own recipe!

  • In potions.cpp, write part1 and part2 — using std::stack.

  • make example should print CMZ and MCD.

  • make input reveals your words!

Today, you built a data structure

Defined the Stack ADT: push, pop, empty. Last in, first out
Implemented two ways: linked list and vector
Analyzed push and pop are \(\Theta(1)\) for linked list. For the vector, doubling on resize keeps the functions \(\Theta(1)\) on average.
Applied Potion Pantry: use a stack to reverse the pile!