{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}


09-Stack-And-Queue-Examples - CS106X Autumn 2010 Handout 09...

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

View Full Document Right Arrow Icon
CS106X Handout 09 Autumn 2010 September 24 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; } } Read Chapter 3 and begin reading Chapter 4. Chapter 4 is dedicated to a client-side treatment of the CS106 container classes like Vector , Grid , Stack , Queue , and so forth.
Background image of page 1

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

View Full Document Right Arrow Icon
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.
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 5

09-Stack-And-Queue-Examples - CS106X Autumn 2010 Handout 09...

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

View Full Document Right Arrow Icon bookmark
Ask a homework question - tutors are online