ADTs continued: Stacks

So far: Vector (for 1-D data) and Grid (for 2-D data)

A new ADT: the Stack.

Stacked examples:

Stack syntax

#include "stack.h" 
Stack nums;
nums.push(1); 
nums.push(3); 
nums.push(5); 
cout << nums.peek() << endl; // 5 
cout << nums << endl; // {1, 3, 5} 
nums.pop(); // nums = {1, 3} 
s.isEmpty()  O(1)  returns true if stack has no 

Member functions
s.isEmpty() O(1) returns true if stack has no elements
s.peek() O(1) returns top value without removing it; throws an error if stack is empty
s.pop() O(1) removes top value and retuns it; throws an error if stack is empty
s.push(value) O(1) places given value on top of stack, increasing its size by one
s.size() O(1) returns number of elements in stack.

Stack limitations/patterns

Exercise: Sentence Reversal

Solution 1: use istringstream.

Solution 2: do it by hand

void printSentenceReverse(const string &sentence) {  
    Stack<string> wordStack;  
    for (char c : sentence) {  
        if (c == ' ') {  
            wordStack.push(word);  
            word = ""; // reset  
        } else {  
            word += c;  
        }  
    }  
    if (word != "") {  
        wordStack.push(word);  
    }  
    cout << " New sentence: ";  
    while (!wordStack.isEmpty()) {  
        word = wordStack.pop();  
        cout << word << SPACE;  
    }  
    cout << endl; 
} 

In summary: when to use what?

Mapping to C++ STL functions

Member functions (first Stanford function, then STL function, then description): reference http://www.cplusplus.com/reference/stack/stack/:
s.isEmpty() s.empty() returns true if stack has no elements
s.peek() s.top() returns top value without removing it; throws an error if stack is empty
s.pop() s.pop() C++ STL version only removes top value (but does not return it); throws an error if stack is empty
s.push(value) s.push(value) places given value on top of stack, increasing its size by one
s.size() s.size() returns number of elements in stack.