CS22 Algorithms ad Data Structures MW :00 am - 2: pm, MSEC 0 Istructor: Xiao Qi Lecture 6: Stacks ad Queues Aoucemets Quiz results Homework 2 is available Due o September 29 th, 2004 www.cs.mt.edu~xqicoursescs22 push(4) pop() top 2 top 4 NodeType * = ew NodeType; ->data = ; ->ext = top; top = ; = NULL; 4 Value stored i the top has to be retured before ode ca be deleted NodeType * = top; top = top->ext; it returvalue = ->data; delete ; top() Applicatios of Stacks top 4 retur top->data; Examiig programs to see if symbols balace properly. (Bracket matchig) Performig postfix calculatios. Performig ifix to postfix coversios. Fuctio calls (ad especially recursio) rely upo stacks.
Symbol Balacig A useful tool for checkig your code is to see if the (), {, ad [] symbols balace properly. For example the sequece [ ( ) ] is legal but the sequece [ ( ] ) is ot. The presece of oe misplaced symbol ca result i hudreds of worthless compiler diagostic errors! Symbol Balacig Algorithm The algorithm is simple ad efficiet: Make a empty stack. Read characters util ed of file (EOF). If the character is a opeig symbol ([{, push it oto the stack. If it is a closig symbol )], the if the stack is empty report a error. Otherwise pop the stack. If the symbol popped is ot the correspodig opeig symbol, report a error. At EOF, if the stack is ot empty report a error. Example Postfix Calculator class StackNode { private: it elemet; StackNode *ext; public: StackNode (cost it &theelemet, StackNode * = NULL) : elemet(theelemet), ext() { Push the { o the stack. Push the ( o the stack. See the ) ad pop the (. Everythig OK. Push the (, see the ), ad pop the (. OK. Push the (, see the ), ad pop the (. OK. Push the {, see the, ad pop the {. OK. See the, pop the origial {. All OK. What is postfix? It is the most efficiet method for represetig arithmetic expressios. With ifix (the method you are used to) you put operators betwee operads: a b. With postfix you put operators after operads: a b. There is ever ay eed to use () s with postfix otatio. There is ever ay ambiguity. Postfix Example This example is i ifix: a b * c (d * e f) * g I postfix this is: a b c * d e * f g * b*c a b*c d*e f d*e g * (f d*e) Postfix Calculator Algorithm The algorithm is simple ad efficiet O(N): Read i iput. If iput is a operad, push o stack. If iput is a operator, pop top two operads off stack, perform operatio, ad place result o stack. Example: a b c * Push a, b, ad the c o the stack. Pop c ad b, perform multiplicatio, ad push result. Pop (b*c) ad a, perform additio, ad push result. (a b*c) (g * (f d*e)) 2
Ifix to Postfix Coversio Surprisigly, oe oly eeds a stack to write a algorithm to covert a ifix expressio to a postfix expressio. It ca hadle the presece of () s. It is efficiet: O(N). Coversio Algorithm The algorithm is reasoably simple: Read ifix expressio as iput. If iput is operad, output the operad. If iput is a operator, -, *,, the pop ad output all operators of >= precedece. Push operator. If iput is (, the push. If iput is ), the pop ad output all operators util see a ( o the stack. Pop the ( without output. If o more iput the pop ad output all operators o stack. Coversio Example Details of Example Ifix: a b * c (d * e f) * g I postfix this is: a b c * d e * f g * Try to follow the algorithm to obtai the right postfix expressio. Output: Stack: ab c * d e * f g * * Arrows represet pop ad output ( * ( Arrows represet pop ad output ( * Fuctio Calls Example I almost all programmig laguages, callig a fuctio ivolves the use of a stack. Whe there is a fuctio call, all of the importat iformatio (values of variables etc.) is stored o a stack, ad cotrol is trasferred to the ew fuctio. This is especially importat durig recursio. Factorial of Retur Factorial of 2 2 * factorial() Factorial of 3 3 * factorial(2) Factorial of 4 4 * factorial(3) Factorial of * factorial(4) 2 6 24 log factorial (it ) { if ( <= ) retur ; else retur * factorial(-); 20 3
Stack Overflow Problems The factorial program is a example of tail recursio, where the recursive call occurs at the lie of the program. Probably exceed the stack limit i your operatig system Probably exceed the capacity of your itegers or eve doubles. Queues A queue is a waitig lie Both eds are used: oe for addig elemets ad oe for removig them. FIFO structure: First i, First out Queues A series of operatios executed o a queue Equeue(0) Equeue() dequeue Equeue() Equeue() dequeue 0 0 Queue ADT Data: A collectio of homogeeous elemets arraged i a sequece. Elemets are iserted to the ed ad removed from the Operatios: Equeue Dequeue IsEmpty El Implemetatio Details Cotiguous memory Usig a circular array Liked lists Usig a ode structure to store data ad a poiter to the ext ode: a chai of odes Queue Implemetatio via Arrays equeue() equeue(6) 4 4 6 if (!iffull()) { if (==size- ==-) { storage[0]= el; = 0; if ( == -) = 0; else { ; storage[]= el; 4
Queue Implemetatio via Arrays equeue() 2 4 3 2 4 3 if (!iffull()) { if (==size- ==-) { storage[0]= el; = 0; if ( == -) = 0; else { ; storage[]= el; Queue Implemetatio via Arrays 4 Value stored i the tmp has to be retured before is updated tmp = storage[]; if ( = ) = = -; else if ( = size ) = 0; else ; retur tmp == OR == 0 ad == size ; Queue Implemetatio via Arrays 4 4 Queue is empty tmp = storage[]; if ( = ) = = -; else if ( = size ) = 0; else ; retur tmp Queues usig Liked Lists Implemetatio of queues usig liked lists resembles the implemetatio of doubly liked lists with some operatios beig restricted Beig a queue we have oly oe isert operatio called equeue(). I may ways push is the same as isert i the We have also oe delete operatio called This operatio is the same as the operatio delete from the The other importat operatios i a stack, called () ad isempty(), do't modify the structure Pictorial view of a queue equeue() 2 2 NodeType * = ew NodeType; ->data = ; ->prev = ; ->ext = NULL; ->ext = ; = ; = NULL;
equeue() equeue() 2 2 NodeType * = ew NodeType; ->data = ; ->prev = ; ->ext = NULL; ->ext = ; = ; = NULL; NodeType * = ew NodeType; ->data = ; ->prev = ; ->ext = NULL; ->ext = ; = ; = NULL; equeue() equeue() 2 2 NodeType * = ew NodeType; ->data = ; ->prev = ; ->ext = NULL; ->ext = ; = ; = NULL; NodeType * = ew NodeType; ->data = ; ->prev = ; ->ext = NULL; ->ext = ; = ; = NULL; NULL 2 2 NodeType * = ; = ->ext; ->prev = NULL; it returvalue = ->data; delete ; NodeType * = ; = ->ext; ->prev = NULL; it returvalue = ->data; delete ; 6
The value has to be "saved" to a orary variable before the ode ca be deleted 2 2 NodeType * = ; = ->ext; ->prev = NULL; it returvalue = ->data; delete ; NodeType * = ; = ->ext; ->prev = NULL; it returvalue = ->data; delete ; 2 NodeType * = ; = ->ext; ->prev = NULL; it returvalue = ->data; delete ;