180 likes | 184 Vues
Introduction to Data Structure. Chapter 7 Ming Li Department of Computer Science California State University, Fresno Fall 2006. Stacks. A stack is a sequence of items that are accessible at only one end of the sequence. Pushing/Popping a Stack.
E N D
Introduction to Data Structure Chapter 7 Ming Li Department of Computer Science California State University, Fresno Fall 2006
Stacks • A stack is a sequence of items that are accessible at only one end of the sequence.
Pushing/Popping a Stack • Because a pop removes the item last added to the stack, we say that a stack has LIFO (last-in/first-out) ordering.
Stack Operations stack(); Create an empty stack. bool empty(); Check whether the stack is empty. Return true if it is empty and false otherwise. int size() const; Return the number of items on the stack. T& top() const; 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().
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.
Stack - Copying while(!s.empty()) s.pop(); s.pop(); int i=0; while(i++<7) s.push(a[7-i]); s.push(a[7]);
Stack - Reversal while(!s.empty()) s.pop(); s.pop(); int i=0; while(i++<7) s.push(a[i]); s.push(a[0]);
Stack – Traversal & Search while(!s.top() !=6) s.pop(); if (s.pop() != 6) s.pop();
Stack – Insertion if (s.pop() < 6) { s1.push(s.top()); s.pop(); } while(!s.top() < 6) { s1.push(s.top()); s.pop(); } s.push(6); while(!s1.empty()) { int x = s1.top(); s.push(x); } while(!s.top() < 6) { s1.push(s.top()); s.pop(); } s.push(6); while(!s.top() < 6) { s1.push(s.top()); s.pop(); }
Stack Problem • How to access min() with O(1), i.e., constant time? • Postfix evaluation • Memory management