Download presentation
Presentation is loading. Please wait.
Published bySolomon Green Modified over 9 years ago
1
1 Stacks Stack Examples Stack API More Examples/Uses Base Conversion Activation Records RPN Implementing a Stack Stacks
2
2 Stacks Three container adapters – stack: LIFO discipline – queue: FIFO – priority_queue: HPFO Stack – – Access only top – Underlying sequence container: deque – No iterators
3
3 Stack Example string str1, str2; stack s; cin >> str1; for (size_t i = 0; i < str1.length (); ++i) s.push (str1[i]); while (! s.empty ()) { str2 += s.top (); s.pop (); } // for boolalpha cout << boolalpha << (str1 == str2) << endl;
4
4 CLASS stack Constructor stack (); Create an empty stack CLASS stack Operations bool empty () const; Check whether the stack is empty. Return true if it is empty and false otherwise.
5
5 CLASS stack Operations void pop (); Remove the item from the top of the stack. Precondition:The stack is not empty. Postcondition:Either the stack is empty or the stack has a new topmost item from a previous push. void push (const T& item); Insert the argument item at the top of the stack. Postcondition: The stack has a new item at the top.
6
6 CLASS stack Operations size_t size () const; Return the number of items on the stack. T& top (); Return a reference to the value of the item at the top of the stack. Precondition:The stack is not empty. const T& top () const; Constant version of top ().
7
7 Base Conversion (Hex) int num = 431, base = 16; stack s; string digits = “0123456789ABCDEF”; do { s.push (digits[num % base]); num /= base; } while (num != 0);
8
8
9
9
10
10 Implementing a Stack typedef int value_type; class Stack { vector v; public: Stack () { } // empty to start // const version too value_type& top () { return (??); } void push (const value_type& i) { ?? } void pop () { ?? } bool empty () const { return (??) } size_t size () const { return (??); } };
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.