Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues.

Similar presentations


Presentation on theme: "Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues."— Presentation transcript:

1 Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues

2 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Stacks A list of items and a pointer to the "top" item in the list. Items can be inserted or removed from the list only at the top the list is ordered in the sequence of entry of items. Insertions and removals proceed in the "LIFO" last- in-first-out order. Functions:  Push: for putting objects into the stack  Pop: for taking objects out of the stack

3 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Stack Class Declaration # include typedef char DataType; const int MaxStackSize=50; class Stack { private: DataType stacklist[MaxStackSize]; int top; public: Stack(void); // constructor to initialize top //modification operations void Push(const DataType& item); DataType Pop(void); void ClearStack(void); //just copy top item without modifying stack contents DataType Peek(void) const; //check stack state int StackEmpty(void) const; int StackFull(void) const; };

4 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Stack Class Implementation Stack::Stack(void):top(-1) {} //Push void Stack::Push(const DataType& item)//same as //Push(DataType item) { //can not push if stack has exceeded its limits if (top==MaxStackSize-1) { cerr<<"Stack overflow"<<endl; exit(1); } // increment top ptr and copy item into list top++; stacklist[top] =item; } //pop DataType Stack::Pop(void) { DataType temp; // is stack empty nothing to pop if (top==-1) { cerr<<"Stack empty"<<endl; exit(1); } //record the top element temp=stacklist[ top] ; //decrement top and return the earlier top element top--; return temp; } //Peek is the same as Pop, except top is not moved DataType Stack::Peek(void) const {// write Peek as exercise } //Stack Empty int Stack::StackEmpty(void) const { return top==-1; //value is 1 if equal, 0 otherwise } // Stack Full int Stack::StackFull(void)const { return top==MaxStackSize-1; } //Clear Stack void Stack::ClearStack(void) { top=-1; }

5 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Stack Example Example: Write a program that uses a stack to test a given character string and decides if the string is a palindrome (i.e. reads the same backwards and forwards, e.g. "kabak", " a man a plan a canal panama", etc.) Algorithm:  first get rid of all blanks in the string  push the whole string character-wise, into a stack  pop out characters one by one, comparing with the characters of the original de-blanked string

6 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Stack Example Assuming that the stack declaration and implementation are in "astack.h“ # include “astack.h" # include void Deblank(char *s, char *t) { while (*s!=NULL) { if (*s!=' ') { *t=*s; t++; } s++; } *t=NULL; //append NULL to newstring } void main() { // create stack object to store string in reverse order. Stack S; char palstring[ 80], deblankedstring[ 80], c; int i=0; // string pointer bool ispalindrome=true; //we'll stop if false // get input cin.getline(palstring,80,'\n'); //remove blanks Deblank(palstring,deblankedstring);// A[],the array;A pointer to A[] //push character onto stack i=0; while(deblankedstring[ i] !=NULL) { S.Push(deblankedstring[ i] ); i++; } //now pop one-by-one comparing with original i=0; while (!S.StackEmpty()) { c=S.Pop(); //get out of loop when first nonmatch if (c!=deblankedstring[i]) { ispalindrome=false; break; } // continue till end of string i++; } //operation finished. Printout result if (ispalindrome) cout<<"\\"<<palstring<<"\\"<<"is a palindrome"<<endl; else cout<<"\\"<<palstring<<"\\"<<"is not a palindrome"<<endl; }

7 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Templates We use typedef to define the data type for the stack items for the stack class Stack class can be used only with that type of data in the program We want to use the same class or function definition for different types of items  Create different objects within the same class but with different data types  Define a general function that works on different data types  Link the data type with the object or function call and not with the whole program  A single function or class definition gives rise to a family of functions or classes that are compiled from the same source code, but operate on different types.  Stack A; Stack B; C++ allows this through Templates

8 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Templates template indicates that T 1,T 2,..T n are classes that will be used with a specific class upon creation of an object Note here that any operation in the template class or function must be defined for any possible data types in the template template int SeqSearch(T list  , int n, T key) /* T is a type that will be specified when SeqSearch is called */ { for (int i=0; i<n; i++) if (list  i  ==key) return i; return -1; } void main() { int A[10], Aindex float M[10], fkey=4.5, Mindex; Aindex=SeqSearch(A,10,25); /*search for int 25 in A */ Mindex=SeqSearch(M,100,fkey); /* search for float 4.5 in M */ }

9 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT A general stack const int MaxStackSize=50; template class Stack { private: T stacklist[MaxStackSize]; int top; public: Stack(void); // constructor to initialize top //modification operations void Push(const T& item); T Pop(void); void ClearStack(void); //just copy top item without modifying stack contents T Peek(void) const; //check stack state int StackEmpty(void) const; int StackFull(void) const; }; template Stack ::Stack(void):top(-1) {} template //Push void Stack ::Push(const T& item)//same as //Push(int item) { //can not push if stack has exceeded its limits if (top==MaxStackSize-1) { cerr<<"Stack overflow"<<endl; exit(1); } // increment top ptr and copy item into list top++; stacklist[top] =item; } template //pop T Stack ::Pop(void) { T temp; // is stack empty nothing to pop if (top==-1) { cerr<<"Stack empty"<<endl; exit(1); } //record the top element temp=stacklist[ top] ; //decrement top and return the earlier top element top--; return temp; }

10 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Example: Arithmetic expression evaluation Arithmetic expressions:  3+2*5=13 Correct  3+2*5=25 Incorrect Parentheses: ((11+1)/2-4 )*3=6 Operator precedence: Low to High: “(“ → -1 “)” → 0 +,- → 1 *, / → 2 exp→ 3 A “(“ starts a new expression which must be calculated before others currently being calculated→ 4 Rule for checking operator-operand matching: rank (state variable) 1. Initialize rank to 0 2. For each operand: add 1 3. For each binary operator: subtract 1 4. For unary operators and parentheses no action For each term the rank should be 0 or 1 For the full expression it must be 1

11 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Example: Arithmetic expression evaluation Two stacks:  Operator stack  Operand stack Algorithm:  Input operand: push it on operand stack  Input operator: Pop all operators which have stack precedence higher than or equal to the precedence of current operators  As operators are popped execute the operation on top stack operands, push result back.  e.g. input is “)“: Pop and evaluate all operators that are in the stack and have stack precedence greater than or equal to the input precedence of “)”  (Note that as stack precedence of “(“ is - 1, this loop stops when “(” is found and popped.) At end of expression: flush the operator stack evaluating operations. The rank must be 1. If rank <1 →operand missing. While clearing stack if “(“ found → ”)” missing. Final result: left on stack top CHECK Preiss book stack applications for a different example

12 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Example e.g. (3+5)/2e3 ((X oprinopn (33 +(+( +3 +(+( 5 5353 )8 Operator input -1 Operand input Operator input 1 Operand input Operator input 0 Pop + (higher precedence) Evaluate + Pop ( Push 8 on stack //8 oprinopn /2 2828 e/e/ e 2828 e/e/ 3 328328 / 8888 Operator input 2 Operand input Operator input 3 Operand input Pop / Evaluate / Push 1 on stack 1 Operator input 0 Evaluate + Pop ( e/e/ 3 328328 Pop e Evaluate e Push 8 on stack Finished Flush stack

13 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Queues A queue is a data structure that stores elements in a list and permits data access only at the two ends of the list. An element is inserted only at the “rear” end of the list and deleted from only the “front” end of the list. Elements are removed in the same order in which they are stored and hence a queue provides FIFO(first-in/first-out) or FCFC(first- come/first-served) ordering

14 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT Queues 0 1 2 3 f,r c=0 2. insert `A’: f c=1r 3. insert `B’: fc=2 r AB 4. insert `C’: f c=3r A ABC 1. initially: count=0, front=0, rear=0 5. delete: f c=2r ABC not accessible any more 6. insert `D’: f c=3 r BCD NOTE: CIRCULAR OPERATION i.e., move rear & front forward: rear=(rear+1)%MaxQSize front=(front+1)%MaxQSize etc.

15 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT A General Queue # include const int MaxQSize=50; template class Queue { private: // queue array and its parameters int front, rear, count; T qlist[ MaxQSize] ; public: //constructor Queue(void); // initialize data members //queue modification operations void Qinsert(const T& item); T QDelete(void); void ClearQueue(void); // queue access T QFront(void) const; // queue test methods int QLength(void) const; int QEmpty(void) const; int QFull(void) const; }; // Queue constructor //initialize queue front, rear, count template Queue ::Queue(void): front(0), rear (0), count(0) {} //Queue Operations // Qinsert: insert item into the queue template void Queue ::Qinsert(const T& item) { // terminate if queue is full if (count==MaxQSize) { cerr<<"Queue overflow!" <<endl; exit(1) } //increment count, assign item to qlist and update rear count++; qlist[ rear] =item; rear=(rear+1)% MaxQSize; } //QDelete : delete element from the front of the queue and return its value template T Queue ::QDelete(void) { T temp; // if qlist is empty, terminate the program if (count==0) { cerr<<"Deleting from an empty queue!"<<endl; } //record value at the front of the queue temp=qlist[ front] ; //decrement count, advance front and return former front count --; front=(front+1) % MaxQsize; return temp; }

16 Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT References Data Structures with C++, William H. Ford,William R. Topp http://www.brpreiss.com/books/opus4/ http://vision1.eee.metu.edu.tr/~vision/LectureNot es/EE441/ch1/classes.html http://vision1.eee.metu.edu.tr/~vision/LectureNot es/EE441/ch1/classes.html http://www.research.att.com/~bs/glossary.html


Download ppt "Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues."

Similar presentations


Ads by Google