09-Stack-And-Queue-Examples

# 09-Stack-And-Queue-Examples - CS106B Winter 2010 Handout 09...

This preview shows pages 1–3. Sign up to view the full content.

CS106B Handout 09 Winter 2010 January 11 th , 2010 Stacks and Queues Stack Primer The stack container is a data structure that’s like a Vector , save that insertions and deletions occur at index 0. Here’s the reduced interface for the Stack : template <typename T> class Stack { public: Stack(); ~Stack(); bool isEmpty(); int size(); void push(T elem); T pop(); }; In principle, we could just use a Vector and limit all insertAt and removeAt calls to involve index 0, but a dedicated Stack class is better because: o its method names are more descriptive, invoke to illusion of a true stack of plates at a cafeteria, and often contribute to a better narrative as to how an algorithm is working, and o it can be optimized to make insertion and deletion much faster than the Vector can. The Stack has the advantage of knowing that all operations impact one end of the container, so it can optimize for that. The Vector is more general and can’t easily optimize that at the expense of equally important insertion and deletion points. Simple Example void PrintLinesInReverse(ifstream& infile) { Stack<string> lines; while (true) { string line; getline(infile, line); if (inline.fail()) break; lines.push(line); } while (!lines.isEmpty()) { cout << lines.pop() << endl; } } Begin reading Chapter 4. It’s dedicated to a client-side treatment of the CS106 container classes like Vector , Grid , Stack , Queue , and so forth.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 Calculator Example /** * Returns true iff the provided character is one of * the binary arithmetic operators we've elected to * support. */ bool IsSupportedOperator(char op) { switch (op) { case '+': case '-': case '*': case '/': case '%': return true; default: return false; } } /** * Computes and returns the integer that results when the integer * values identified via first and second are combined using * the supplied (presumably legitimate) operator. */ int Compute(int first, char op, int second)
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 03/07/2010 for the course CS 201 taught by Professor Selimaksoy during the Spring '09 term at Bilkent University.

### Page1 / 5

09-Stack-And-Queue-Examples - CS106B Winter 2010 Handout 09...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online