The Abstract Data Type Stack Simple Applicatins f the ADT Stack Implementatins f the ADT Stack Applicatins 1
The Abstract Data Type Stack 3 ADT STACK Examples readandcrrect algrithm abcc ddde ef fg Output: abcdefg Hw can a prgram read the riginal line and get the crrect input? Hw t stre the input line? ADT apprach, pstpne decisin fr cnsidering what peratins yu will need t perfrm n the data? 2
ADT STACK The Abstract Data Type: readandcrrect algrithm Read the line, crrecting mistakes alng the way abcc ddde ef fg Add a new item t the ADT Remve frm the ADT the item that was added mst recently Determine whether the ADT is empty Retrieve frm the ADT the item that was added mst recently while(nt end end f f input){ input){ read a new new character ch ch if(ch is is nt nt a a ){ ){ Add ch t the ADT Add ch t the ADT else if ( the ADT is nt empty ){ else { remve frm the ADT the item added mst recently remve frm the ADT the item added mst recently else { Ignre the ADT STACK 3
ADT STACK ADT stack peratins Create an empty stack Determine whether a stack is empty Add a new item t the stack Remve frm the stack the item that was added mst recently Remve all the items frm the stack Retrieve frm the stack the item that was added mst recently ADT STACK Pseudcde fr the ADT stack peratins createstack() // Creates an empty stack. isempty() // Determines whether a stack is empty. push(newitem) thrws StackExceptin // Adds newitem t the tp f the stack. // Thrws StackExceptin if the insertin is nt successful. pp() thrws StackExceptin // Retrieves and then remves the tp f the stack. // Thrws StackExceptin if the deletin is nt successful. ppall() // Remves all items frm the stack. peek() thrws StackExceptin // Retrieves the tp f the stack. Thrws StackExceptin if the retrieval is nt successful Stack tp items createstack() isempty() push() pp() ppall() peek() 4
ADT STACK A stack Last-in, first-ut (LIFO) prperty The last item placed n the stack will be the first item remved Analgy A stack f dishes in a cafeteria ADT STACK Using the ADT Stack in a Slutin readandcrrect() Read the input line and returns the crrected versin as a stack astack.createstack(); Read newchar While (newchar is nt the end-f-line symbl) { if (newchar is nt a ){ astack.push(newchar) else if (!astack.isempty( )){ ldchar=astack.pp( ) Read newchar retuen astack 5
ADT STACK Thinking Example: S.pp(); S.push(c); S.push(b); S.pp(); S.peek(); S.push(a); S.peek(); S.push(b); S.pp(); S.push(c); Simple Applicatins f the ADT Stack 12 6
SIMPLE APPLICATIONS Checking the balanced braces A stack can be used t verify whether a prgram cntains balanced braces An example f balanced braces abc{defg{ijk{l{mnpqr An example f unbalanced braces abc{def{ghij{klm Requirements fr balanced braces Each time yu encunter a, it matches an already encuntered { When yu reach the end f the string, yu have matched each { Each successive clse brace with the mst recently encuntered unmatched pen brace { SIMPLE APPLICATIONS Checking the balanced braces astack.createstack(); balancedsfar= true; i=0; while(balancedsfar and i<length f astring){ ch=character at psitin i in astring; ++i; If(ch is { )// push an pen brace { astack.push( { ); else if (ch is )//clse brace { if(!astack.isempty()) { penbrace=astack.pp();//pp a matching pen brace else{ balancedsfar=false; 7
SIMPLE APPLICATIONS Checking the balanced braces SIMPLE APPLICATIONS Recgnizing Strings in a Language Language L L = {w$w : w is a pssible empty string f characters ther than $, w = reverse(w) A stack can be used t determine whether a given string is in L Traverse the first half f the string, pushing each character nt a stack Once yu reach the $, fr each character in the secnd half f the string, pp a character ff the stack Match the ppped character with the current character in the string 8
SIMPLE APPLICATIONS Thinking L = {w$w: w is a pssible empty string f characters ther than $ e.g. ab$ab, aacc$aacc, aacc$ccaa Can we use stack t verify the string by scanning the string nly nce? Why? Implementatins f the ADT Stack 18 9
Implementatins f the ADT stack The ADT stack can be implemented using StackExceptin Stack tp items An array createstack() isempty() A linked list push() The ADT list pp() ppall() StackInterface peek() Prvides a cmmn specificatin fr all implementatins Implementatins f the ADT stack Array-based implementatin f the ADT stack StackArrayBased class Implements StackInterface Instances Stacks Private data fields An array f Objects called items The index tp Cnstructr replaces the ADT peratin createstack Stack tp items createstack() isempty() push() pp() ppall() peek() 10
Implementatins f the ADT stack A reference-based implementatin f the ADT stack Required when the stack needs t grw and shrink dynamically StackReferenceBased Implements StackInterface tp is a reference t the head f a linked list f items Stack tp items createstack() isempty() push() pp() ppall() peek() Implementatins f the ADT stack ADT list-based implementatin f the ADT stack The ADT list can be used t represent the items in a stack If the item in psitin 1 f a list represents the tp f the stack push(newitem) peratin is implemented as add(0, newitem) pp() peratin is implemented as get(0) remve(0) peek() peratin is implemented as get(0) Stack tp items createstack() isempty() push() pp() ppall() peek() 11
Cmparisn All f the three implementatins are ultimately array based r reference based Fixed size versus dynamic size An array-based implementatin Uses fixed-sized arrays Prevents the push peratin frm adding an item t the stack if the stack s size limit has been reached A reference-based implementatin Des nt put a limit n the size f the stack ADT list apprach Reuses an already implemented class Much simpler t write Saves time JCF JCF cntains an implementatin f a stack class called Stack (generic) java.util.stack Derived frm Vectr Includes methds: empty, peek, pp, push, and search search returns the 1-based psitin f an bject n the stack 12
Applicatins 25 Applicatins Algebraic Expressins T evaluate an infix expressins Cnvert the infix expressin t pstfix frm Evaluate the pstfix expressin 13
Applicatins Evaluating Pstfix Expressins A pstfix calculatr Requires yu t enter pstfix expressins Example: 2, 3, 4, +, * When an perand is entered, the calculatr Pushes it nt a stack When an peratr is entered, the calculatr Applies it t the tp tw perands f the stack Pps the perands frm the stack Pushes the result f the peratin n the stack Applicatins 14
Applicatins Evaluating Pstfix Expressins T evaluate a pstfix expressin which is entered as a string f characters Simplifying assumptins The string is a syntactically crrect pstfix expressin N unary peratrs are present N expnentiatin peratrs are present Operands are single lwercase letters that represent integer values Applicatins Cnverting Infix Expressins t Equivalent Pstfix Expressins Facts abut cnverting frm infix t pstfix Operands always stay in the same rder with respect t ne anther An peratr will mve nly t the right with respect t the perands All parentheses are remved 15
Applicatins Initialize pstfixexp t the null string fr (each character ch in the infix expressin){ switch(ch){ case ch is an perand: append ch t the end f pstfixexp break; case ch is ( : astack.push(ch) break; case ch is ) : While (tp f stack is bt ( ){ pstfixexp=pstfixexp+astack.pp(); penparen=astack.pp(); //remve the pen parenthesis break; case ch is an peratr: while(!astack.isempty() and tp f stack is nt ( and precedence(ch)<= precedence(tp f stack)) { pstfixexp=pstfixexp+astack.pp(); astack.push(ch) //save new peratr break; while(!astack.isempty()){ pstfixexp=pstfixexp+astack.pp(); Applicatins Cnverting Infix Expressins t Equivalent Pstfix Expressins a-(b+c*d)/e 16
Applicatins High Planes Airline Cmpany (HPAir) Prblem Fr each custmer request, indicate whether a sequence f HPAir flights exists frm the rigin city t the destinatin city The flight map fr HPAir is a directed graph Adjacent vertices: tw vertices that are jined by an edge Directed path: a sequence f directed edges Applicatins The slutin perfrms an exhaustive search Beginning at the rigin city, the slutin will try every pssible sequence f flights until either It finds a sequence that gets t the destinatin city It determines that n such sequence exists The ADT stack is useful in rganizing an exhaustive search Backtracking can be used t recver frm a wrng chice f a city 17
Applicatins Pssible utcmes f the recursive search strategy Yu eventually reach the destinatin city and can cnclude that it is pssible t fly frm the rigin t the destinatin Yu reach a city C frm which there are n departing flights Stacks and Recursin The relatinship between stacks and recursin A cmparisn f key aspects f tw search algrithms Visiting a new city Recursive call vs. push stack Backtracking an unvisited city that is adjacent t the current city Frmal parameter vs. tp f stack Terminatin Bx trace terminate and result returned vs. stack empty r tp is destinatin 18
Stacks and Recursin The relatinship between stacks and recursin ADT stack has a hidden presence in the cncept f recursin Stacks are used t implement recursive methds Each recursive call generates an activatin recrd that is pushed nt a stack Yu can use stacks when implementing a nnrecursive versin f a recursive algrithm HOMEWORK Read thrugh Chapter 7 19