fall 2006 metu eeeee 441 s. ece (guran) sch midt ee 441 data structures lecture 6 stacks and queues

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

Upload: samuel-butler

Post on 18-Jan-2018

217 views

Category:

Documents


1 download

DESCRIPTION

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; };

TRANSCRIPT

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

Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH

MIDT

EE 441 Data StructuresLecture 6

Stacks and Queues

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

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

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

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT

Stack Class Declaration# include <iostream.h># include <stdlib.h>

typedef char DataType;const int MaxStackSize=50;class Stack{private:DataType stacklist[MaxStackSize];int top;public:Stack(void); // constructor to initialize top//modification operationsvoid Push(const DataType& item);DataType Pop(void);void ClearStack(void);//just copy top item without modifying stack contentsDataType Peek(void) const;//check stack stateint StackEmpty(void) const;int StackFull(void) const;};

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

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT

Stack Class ImplementationStack::Stack(void):top(-1){}

//Pushvoid Stack::Push(const DataType& item)//same as

//Push(DataType item) {//can not push if stack has exceeded its limitsif (top==MaxStackSize-1){cerr<<"Stack overflow"<<endl;exit(1);}// increment top ptr and copy item into listtop++;stacklist[top] =item;}

//popDataType Stack::Pop(void){DataType temp;// is stack empty nothing to popif (top==-1){ cerr<<"Stack empty"<<endl;exit(1);}//record the top elementtemp=stacklist[ top] ;//decrement top and return the earlier top elementtop--;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;}

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

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

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

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT

Stack ExampleAssuming that the stackdeclaration and implementationare in "astack.h“# include “astack.h"# include <iostream.h>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 pointerbool ispalindrome=true; //we'll stop if false

// get input

cin.getline(palstring,80,'\n');//remove blanksDeblank(palstring,deblankedstring);// A[],the array;A pointer

to A[]//push character onto stacki=0;while(deblankedstring[ i] !=NULL){S.Push(deblankedstring[ i] );i++;}//now pop one-by-one comparing with originali=0;while (!S.StackEmpty()){c=S.Pop();//get out of loop when first nonmatchif (c!=deblankedstring[i]){ispalindrome=false;break;}// continue till end of stringi++;}//operation finished. Printout resultif (ispalindrome)cout<<"\\"<<palstring<<"\\"<<"is a palindrome"<<endl;elsecout<<"\\"<<palstring<<"\\"<<"is not a palindrome"<<endl;}

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

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 <float> A; Stack<char> B;

C++ allows this through Templates

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

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT

Templates template <class T1,

class T2, …classTn> indicates that T1,T2, ..Tn 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 <class T>

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 (listi==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 */

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

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT

A general stackconst int MaxStackSize=50;template <class T>class Stack{private:T stacklist[MaxStackSize];int top;public:Stack(void); // constructor to

initialize top//modification operationsvoid Push(const T& item);T Pop(void);void ClearStack(void);//just copy top item without

modifying stack contentsT Peek(void) const;//check stack stateint StackEmpty(void) const;int StackFull(void) const;};

template <class T>Stack<T>::Stack(void):top(-1){}

template <class T>//Pushvoid Stack<T>::Push(const T& item)//same as //Push(int

item) {//can not push if stack has exceeded its limitsif (top==MaxStackSize-1){cerr<<"Stack overflow"<<endl;exit(1);}// increment top ptr and copy item into listtop++;stacklist[top] =item;}template <class T>//popT Stack<T>::Pop(void){T temp;// is stack empty nothing to popif (top==-1){ cerr<<"Stack empty"<<endl;exit(1);}//record the top elementtemp=stacklist[ top] ;//decrement top and return the earlier top elementtop--;return temp;}

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

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*, / → 2exp→ 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 02. For each operand: add 13. For each binary operator: subtract 14. 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

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

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

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

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT

Examplee.g. (3+5)/2e3

(( X

oprin opn

(3 3

+(+ 3

+(5 5

3

) 8

Operator input -1

Operand input

Operator input 1

Operand input

Operator input 0Pop + (higher precedence)

Evaluate +Pop (

Push 8 on stack

// 8

oprin opn

/2 28

e/e 2

8

e/

3328

/ 88

Operator input 2

Operand input

Operator input 3

Operand input

Pop /Evaluate /

Push 1 on stack

1Operator input 0

Evaluate +Pop (

e/

3328

Pop eEvaluate e

Push 8 on stack

Finished

Flush stack

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

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

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

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT

Queues 0 1 2 3

f,r c=02. insert `A’:

f c=1r3. insert `B’:

f c=2r

A B

4. insert `C’:

f c=3r

A

A B C

1. initially: count=0, front=0, rear=0 5. delete:

f c=2r

A B C

not accessible any more

6. insert `D’:

f c=3r

B C D

NOTE: CIRCULAR OPERATIONi.e., move rear & front forward:rear=(rear+1)%MaxQSizefront=(front+1)%MaxQSize etc.

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

Fall 2006 METU EEE EE 441 S. Ece (GURAN) SCHMIDT

A General Queue

# include <iostream.h># include <stdlib.h>

const int MaxQSize=50;

template <class T>class Queue

{private:

// queue array and its parameters

int front, rear, count;T qlist[ MaxQSize] ;

public:

//constructor

Queue(void); // initialize data members//queue modification operationsvoid Qinsert(const T& item);T QDelete(void);void ClearQueue(void);// queue accessT QFront(void) const;// queue test methodsint QLength(void) const;int QEmpty(void) const;int QFull(void) const;};

// Queue constructor

//initialize queue front, rear, counttemplate <class T>Queue<T>::Queue(void): front(0), rear (0), count(0){}//Queue Operations// Qinsert: insert item into the queuetemplate <class T>void Queue<T>::Qinsert(const T& item){// terminate if queue is fullif (count==MaxQSize){ cerr<<"Queue overflow!" <<endl;exit(1)}//increment count, assign item to qlist and update rearcount++;qlist[ rear] =item;rear=(rear+1)% MaxQSize;}

//QDelete : delete element from the front of the queue and return its value

template <class T>T Queue<T>::QDelete(void){T temp;// if qlist is empty, terminate the programif (count==0){cerr<<"Deleting from an empty queue!"<<endl;}//record value at the front of the queuetemp=qlist[ front] ;//decrement count, advance front and return former frontcount --;front=(front+1) % MaxQsize;return temp;}

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

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://www.research.att.com/~bs/glossary.html