+ All Categories
Home > Documents > Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack...

Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack...

Date post: 19-Dec-2015
Category:
Upload: austen-gyles-james
View: 410 times
Download: 5 times
Share this document with a friend
Popular Tags:
57
Data Structures( Data Structures( 数数数数 数数数数 ) ) Course 4:Stack Course 4:Stack
Transcript
Page 1: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

Data Structures(Data Structures( 数据结数据结构构 ))

Course 4:Stack Course 4:Stack

Page 2: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

2西南财经大学天府学院

VocabularyVocabularyStack 堆栈Stack Top 栈顶Push stack 入栈Pop stack 出栈Overflow 上溢出Underflow 下溢出Parse 解析LIFO 后进先出

Page 3: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

3西南财经大学天府学院

Stack definitionStack definition

Stack of books

The questions are:

1.How to add a book to the stack?2.How to take the third book from top?

A stack is a last in-first out (LIFO) data structure in which all insertion and deletion are restrict to one end, called top.

Page 4: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

4西南财经大学天府学院

Understand stackUnderstand stack

You can imagine stack as this barrel, when you want to put the black pie into the barrel, you just put it on the top of the orange one. Meanwhile, when you want to get the red pie, you should first popup the other two pies, and then you can get the red one.

Page 5: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

5西南财经大学天府学院

Basic stack operationsBasic stack operations

Push stackBe careful of the situation of stack overflow.

Pop stackBe careful of the situation of stack underflow.

Stack top

Page 6: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

6西南财经大学天府学院

Push stackPush stack

DATA

PUSH

DATA

DATA

Push operation adds an item at the top of the stack. Before adding the item, the stack space must be checked to ensure that there is enough room to hold the item.

Page 7: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

7西南财经大学天府学院

POP StackPOP Stack

POP

DATA

POP removes the item at the top of the stack and return the item to the user(the application that calls this operation). Be careful the empty state or underflow state of the the stack, when you implement pop operation.

Page 8: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

8西南财经大学天府学院

Stack topStack top

Stack Top

DATA

Stack Top copies the item at the top of the stack and return the item to the user(the application that calls this operation), but does not remove the item. Be careful the empty state or underflow state of the the stack, when you implement stack top operation.

Page 9: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

9西南财经大学天府学院

Example of basic stack operationsExample of basic stack operations

Blue

Red

Green

Push “Green”

Blue

Red

Green

Push “Blue”Red

Green

Blue

POPRed

Green

Blue

PUSH Red

Green

Blue

Red

STACKTOP

Green

Red

Red

POP

Green

Red

POP

Green

Page 10: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

10西南财经大学天府学院

Page 11: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

11西南财经大学天府学院

STACK LINKED LIST STACK LINKED LIST IMPLEMENTATIONIMPLEMENTATION

Several data structure can be used to implement stack.

Sequential structure (array)Linked list structure

Page 12: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

12西南财经大学天府学院

The Structure of Stack Head and The Structure of Stack Head and Stack nodeStack node

Meta data Top

Stack Data Next

Stack Head structure

Stack Data structure

Pointer to

node

stack count <integer> top <node pointer>end stack

node data <datatype> next <node pointer>end node

Page 13: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

13西南财经大学天府学院

Stack Algorithms and Pseudocode Stack Algorithms and Pseudocode implementationimplementation

Create stackPush stackPop stackStack topEmpty StackFull stackStack countDestroy stack

Page 14: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

14西南财经大学天府学院

Create stackCreate stack

Create stack just initialize the metadae for the stack structure.

?count

?Top

0count

×Top

algorithm creatStack(ref stack <metadata>

Initialize metadata for a stack. Pre Stack is structure for

metadata. Post metadata initialized1 stack.count=02 stack.top=null3 Returnend createStack

Page 15: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

15西南财经大学天府学院

Push StackPush Stack

0count

×Top

PUSH Green 1

count Top

Greendata

×next

PUSH Green

Page 16: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

16西南财经大学天府学院

Push Stack (Continue)Push Stack (Continue)

PUSH Blue

1count Top

Greendata

×next

2count Top

bluedata next

Greendata

×next

PUSH Blue

Page 17: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

17西南财经大学天府学院

Push Stack (Pseudocode)Push Stack (Pseudocode)

algorithm pushStack(ref stack <metadata>, val data <dataType>)

Insert (push) one item into the stack.

Pre stack is metadata structure to a valid stack, data contains data to be pushed in stack

Post data have been pushed in stack.

Return true if successful; false is memory overflow.

1 if (stack is full)

1 success=false

2 else

1 allocate(newPtr)

2 newPtr->data=data

3 newPtr->next=stack.top

4 stack.top=newPtr

5 stack.count=stack.count+1

6 success=true

3 endif

4 return success

end pushStack

Page 18: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

18西南财经大学天府学院

Pop StackPop Stack

2count Top

bluedata next

Greendata

×next

1count Top

Greendata

×next

POP StackPOP Stack

Page 19: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

19西南财经大学天府学院

Pop Stack (Continue)Pop Stack (Continue)

1count Top

Greendata

×next

POP Stack

0count

×Top

POP Stack

Page 20: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

20西南财经大学天府学院

Pop Stack (pseudocode)Pop Stack (pseudocode)algorithm popStack(ref stack <metadata>,ref dataOut <dataType>) This algortithm pops the

item on the top of the stack and returns it to the user.

Pre stack is metadata structure to a valid stack

dataOut is a reference variable to receive the data.

Post Data have been returned to calling algorithm.

Return true is successful; false if underflow.

1 If (stack empty) 1 success=false2 Else 1 dltPtr=stack.top 2 dataOut=stack.top->data 3 stack.top=stack.top-

>next 4 stack.count=stack.count-

1 5 recycle (dltPtr) 6 success=true3 end if 4 return successend pop stack

Page 21: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

21西南财经大学天府学院

Stack TopStack Top

The stack top algorithm sends the data at the top of the stack back to the calling module without deleting the top node. The logic for the stack top is simple, but one thing should be taken care, that is the state of stack empty.

Page 22: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

22西南财经大学天府学院

Stack top (pseudocode) Stack top (pseudocode) algorithm stackTop(val stack <metadata>, ref dataOut

<dataType>)This algorithm retrives the data from the top of the stack without

changing the stackPre stack is metadata structure to a valid stack dataOut is a reference variable to receive the dataPost data have been returned to calling algorithm Return data have been returned, false if underflow.1 if (stack empty) 1 success=false2 else 1 DataOut=stack.top->data 2 Success=true3 end if4 return successend stackTop

Page 23: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

23西南财经大学天府学院

Destroy stack (Original state)Destroy stack (Original state)

3count Top

bluedata next

Greendata

×next

Reddata next

Page 24: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

24西南财经大学天府学院

Temp

Reddata next

3count Top

bluedata next

Greendata

×next

Destroy stack (Delete 1Destroy stack (Delete 1stst item) item)

Page 25: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

25西南财经大学天府学院

Destroy stack (Delete 2Destroy stack (Delete 2stst item) item)

3count Top

Greendata

×next

Temp

bluedata next

Page 26: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

26西南财经大学天府学院

Destroy stack (Delete 3Destroy stack (Delete 3stst item) item)

0count

×Top

Temp

Greendata next

Page 27: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

27西南财经大学天府学院

Pseudocode for Destroy Stack Pseudocode for Destroy Stack

algorithm destroystack(ref stack <metadata>)This algorithm releases all nodes back to the dynamic

memory. Pre stack is metadata structure to a valid stack Post stack empty and all nodes recycled1 loop (stack.top not null) 1 temp=stack.top 2 stack.top=temp->next 3 recycle( temp)2 end loop 3 stack.count=04 returnend destroyStack

Page 28: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

28西南财经大学天府学院

Other stack algorithmsOther stack algorithmsFundamental stack operations include create stack, push stack, pop stack, stack top, and destroy stack.In order to totally encapsulate the data and the data structure of the stack. Three simple operations are introduced. They are empty stack, stack count, and full stack.

Page 29: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

29西南财经大学天府学院

Empty stack operation is very simple. Based on linked list implementation. We can just check the head node of the list to determine whether the stack is empty or not. Therefore the pseudocode is very simple.

algorithm emptyStack(val stack <metadata>)Determines whether stack is empty and returns a Boolean. Pre stack is metadata structure to a valid stack Post returns stack status Return Boolean, true:stack empty, false: stack contains

data1 if (stack.top not null) 1 result=false2 else 1 result=true3 end if4 return resultEnd emptyStack

Empty stackEmpty stack

Other condition statement(s) that can

be used here to replace this statement.

Page 30: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

30西南财经大学天府学院

Full stackFull stack

algorithm fullStack(val stack <metadata>)Determines whether stack is full or not and returns a Boolean. Pre stack is metadata structure to a valid stack. Post returns stack status. Return Boolean, true:stack full, false:memory available1 If (memory available) 1 result=false2 else 1 result=true3 end if4 return false5 end fullStack

Based on the linked list implementation of stack, the size of stack is confined within the available memory space. Therefore the algorithm probes the memory space( tries to allocate a block of memory to hold stack data node) to determine whether a stack is full or not.

Page 31: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

31西南财经大学天府学院

Stack CountStack Count

algorithm stackCount(val stack <metadata>)Returns the number of elements currently in stack Pre stack is metadata structure to a valid

stack Post returns stack count Return integer count of number of elements in

stack.1 return (stack.count)end stackCount

There is only one executive statement in this algorithm. Of course, it can be placed in the upper functions and eliminate this algorithm. But do not forget the essence of ADT—hiding the data and the structure absolutely to the upper applications.

Page 32: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

32西南财经大学天府学院

Stack ApplicationsStack Applications

Typical stack applications can be classified into four broad categories: Reversing data Parsing data Postponing data usage Backtracking steps

Page 33: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

33西南财经大学天府学院

Reverse a ListReverse a Listalgorithm reverseNumberThis program reverses a list of integers read from the keyboard

by pushing them into a stack and retrieving them one by one.1 createStack( stack)2 prompt (Enter a number)3 read (number)Fill stack4 loop(not end of data AND not fullStack(stack)) 1 pushStack(stack, number) 2 prompt (Enter next number: <EOF> to stop) 3 read(number)5 end loopNow print numbers in reverse6 Loop (not emptyStack(stack)) 1 popStack(stack dataOut) 2 print(dataOut)7 end loopend reverseNumber

The idea lies in reversing data is very easy to understand. First, push each item one by one into stack(statements 4-5), then pop them out successively (statements 6-7) . Because stack is a LIFO data structure, the order of the item has been reversed.

Page 34: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

34西南财经大学天府学院

Convert decimal to binaryConvert decimal to binary

In order to convert decimal to binary, we can divide decimal number and successive quotients by 2 continuously and record the remainders until the quotient becomes 0, then we print the remainders in backward order.

Stack is an ideal structure to implement this process. While calculating the quotients and remainders, we can push the remainders into a stack. After finishing calculating, we can pop up the remainders and remainders will be naturally in backward order.

Page 35: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

35西南财经大学天府学院

Algorithm decimalToBinaryThis algorithm reads an integer from keyboard and print its binary equivalent. It use a stack to reverse the order of 0’s and 1’s produce.1 createStack(stack)2 prompt (Enter a decimal number to convert to binary) 3 read(number)4 loop (number>0) 1 digit=number modulo 2 2 pushOK=push(stack, digit) 3 if (pushOK false) 1 print (Stack overflow alert) 2 quit algorithm 4 end if 5 number = number / 25 end loopBinary number created in stack, now print it.6 loop (not emptyStack(stack)) 1 popStack(stack, digit) 2 print digit7 end loop8 returnend decimalToBinary

Algorithm Algorithm DecimaltoBinarDecimaltoBinaryy

Page 36: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

36西南财经大学天府学院

Parsing Parsing

Parsing is any logic that breaks data into independent pieces for further processing. For example:

1. Parentheses must be matched in an algebraic expression.2. “/*” and “*/” must be matched in comment statement in a C/C++ source file.3. Stack can hold the left parts of these segments while scanning an expression or a statement for the later comparing.

Page 37: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

37西南财经大学天府学院

Parse parenthesesParse parenthesesAlgorithm parseParensThis algorithm reads a source program and parses it to make sure all opening-closing parentheses are paired.1 loop (more data) 1 read (character) 2 if (character is an opening parenthesis) 1 pushStack (stack, character) 3 else 1 if (character is closing parenthesis) 1 if (emptyStack (stack)) 1 print (Closing parenthesis not matched alert) 2 else 1 popStack(stack,token) 3 end if 4 end if2 end loop3 if (not emptyStack(stack)) 1 print (Opening parenthesis not matched alert)4 end ifend parseParens

Page 38: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

38西南财经大学天府学院

Postponement and arithmetic Postponement and arithmetic expression evaluationexpression evaluation

Postponement means deferring data usage until some later point(or something happens).An arithmetic expression can be expressed in three different ways.Infix, prefix, and postfix. In source program, it is often expressed with infix format, but before an expression is calculated in computer, it is usually transformed into postfix expressions.

Page 39: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

39西南财经大学天府学院

Manual transformationManual transformation

1. Fully parenthesize the expression using any explicit parentheses and the arithmetic precedence-multiply and divide before add and subtract.2.Changing all infix notations in each parenthesis to postfix notation, starting from the innermost expressions3.Remove all parentheses.

Page 40: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

40西南财经大学天府学院

Examples of manual transformationExamples of manual transformation

A+B*C

(A+(B*C))

(A+(BC*))

(A(BC)*+)

ABC*+

(A+B)*C+D+E*F-G

(((((A+B)*C)+D)+(E*F))-G)

(((((AB+)C*)D+)(EF*)+)G-)

AB+C*D+EF*+G-

Page 41: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

41西南财经大学天府学院

Transform expression with Transform expression with stackstack

A*B AB*

1.Read and copy the first operand A to the result, we get “A”.2.Read the operator “*” and push it into a stack for later use.3.Read and copy the second operand B to the result, we can get “AB”.3.Finish scan the source expression, popup the operator and concatenate it to the result, we get “AB*”

Page 42: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

42西南财经大学天府学院

Transform expression with Transform expression with stack (considering priority)stack (considering priority)

A+B*C-D/E ABC*DE/-+

Infix stack postfix

A+B*C-D/E

+B*C-D/E A

B*C-D/E + A

*C-D/E + AB

C-D/E *+

AB

-D/E *+

ABC

D/E - ABC*+

/E - ABC*+D

E/- ABC*+D

/-

ABC*+DE

ABC*+DE/-

Page 43: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

43西南财经大学天府学院

Transform expression with Transform expression with stack(considering parenthesis)stack(considering parenthesis)

A*(B+C/D)-E ABCD/+*E-

Infix Stack Postfix

A*(B+C/D)-E

*(B+C/D)-E A

(B+C/D)-E *

A B+C/D)-E (*

A

+C/D)-E (*

AB

C/D)-E+(*

AB

/D)-E+(* ABC

D)-E/+(*

ABC

)-E/+(*

ABCD

-E* ABCD/+

E

-

ABCD/+*

-

ABCD/+*E

ABCD/+*E-

Page 44: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

44西南财经大学天府学院

Summary of transforming an infix Summary of transforming an infix to a postfix expressionto a postfix expression

Read each item in an infix expression from left to right until to the end of the infix expression, according to the type of item take following different action:

1. If the item is an open parenthesis, push it into stack directly.

2. If the item is a close parenthesis, repeatedly popup an operator in the stack, and append the operator to the postfix expression, until an open parenthesis has been popped out. (discard open and close parenthesis)

3. If the item is an operator, and the priority of the operator is higher that that of top item in the stack, push the operator into the stack. Otherwise, popup each operator in the stack and append it to the postfix expression, until the priority of the item is higher that that of top item in the stack or the stack becomes empty. Then push the current item just got from the infix expression.

4. If the item is an operand, append it to the postfix directly.

5. After finishing scanning infix expression, popup all operators in the stack and append each operator to the postfix expression according to the order it popped up.

Page 45: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

45西南财经大学天府学院

algorithm inToPostFix(val formula <string>)convert infix formula to postfix.Pre Formula is infix notation that has been edited to ensure that there are no syntactical errors.Post postfix formula has been formatted as a string as postfix.Return postfix formula.

1 createStack(stack)2 set postfix to null string3 looper=04 loop (looper<sizeof formula) 1 token =formula[looper] 2 if (token is open parenthesis) 1 pushStack(stack token) 3 elseif (token is close parenthesis) 1 popStack(stack, token tokenOut) 2 loop (tokenOut is not open parenthesis) 1 concatenate token to postfix 2 popStack(stack, tokenOut) 3 end loop

Transforming Transforming AlgorithmAlgorithm

4 elseif (token is operator) 1 stackTop(stack, topToken) 2 loop ( not emptyStack(stack) AND

priority(token)<=priority(topToken)) 1 popStack(stack, tokenOut) 2 concatenate tokenOut to

postfix 3 stackTop(stack,topToken) 3 end loop 4 pushStack (stack, token) 5 else 1 concatenate token to postfix 6 end if 7 looper=looper+15 end loop6 loop (not emptyStack(stack)) 1 popStack(stack, tokenOut) 2 concatenate tokenOut to postfix7 end loop8 return postFixend inToPostFix

Page 46: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

46西南财经大学天府学院

Evaluating Postfix expressionsEvaluating Postfix expressions

Although postfix expression is beyond our habit of reading, it is easy to evaluate, especially with help of stack.While scanning a postfix expression,we can push all operands into a stack for later use, when we meet an operator, we can popup two operands and evaluate them with the operator, then push the result into the same stack. After finishing scanning, the final result will be the last item in the stack.

Page 47: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

47西南财经大学天府学院

2*(4+6) 246+* 20

Postix Stack

246+*

46+* 2

6+* 42

642 +*

* 102

6+4=10

20

Example of postfix expression Example of postfix expression evaluationevaluation

Page 48: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

48西南财经大学天府学院

Evaluating Algorithm Evaluating Algorithm algorithm postFixEvaluate(val expr<string>)This algorithm evaluates a postfix expression and returns it value.Pre a valid expression.Post Postfix value computed.Return value of expression1 exprsize=size of expression string2 createStack(stack)3 index=04 loop (index<exprsize) 1 if (expr[index] is operand) 1 pushStack(stack,expr[index]) 2 else 1 popStack(stack,operand2) 2 popStack(stack,operand1) 3 operator=expr[index] 4 value=calculate(operand1,operator,operand1) 5 pushStack(stack,value) 3 end if 4 index=index+15 end loop6 popStack(stack,result)7 return (result)end postFixEvaluate

Page 49: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

49西南财经大学天府学院

Backtracking Backtracking

Backtracking is widely used in applications such as computer game, decision analysis, expert system, and other Artificial Intelligence system.The most important technique in backtracking is to record the “foot steps” and other choices at “crossway” while advancing. When reaching a dead corner, you can go back along the “foot steps” to the nearest “crossway” and probe another way. You can try repeatedly and strenuously in this fashion until you get your destination or get the result that your destination is unreachable.Stack is an ideal structure to implement recording and backtracking “foot steps” and “branch ways” as its LIFO feature. But how to distinguish “foot step” and “branch way” should be taken into consideration.

Page 50: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

50西南财经大学天府学院

Simple Example of BacktrackingSimple Example of Backtracking

1 2 3

4

12

56 7

89 10 11

13 14 15 16

17 18

Start node

B12321

B12321

B8B954

B12321

B8B954

B12321

End76

B8B954

B12321

End76

B8B954

B12321

End8

B954

B12321

End8

B954

B12321

End1110954

B12321

End1110954

B12321

Goal161514

B171312321

Goal161514

B171312321

(a) (b) (c) (d) (e) (f)

Page 51: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

51西南财经大学天府学院

Seek goal algorithmSeek goal algorithmalgorithm seekGoal(val map<map structure>)This algorithm determines the path to a desired goal.Pre a graph containing the path initialized.Post Path to the goal printed1 createStack(stack)2 pMap=map.start

Find path and save path in stack3 loop (pMap not null AND goalNotFound) 1 if (pMap is goal) 1 set goalNotFound to false 2 else 1 pushStack(stack,pMap) 2 if (pMap is a branch point) 1 loop (more branch points) 1 create branchPoint node) 2 pushStack(stack,branchPoint) 2 end loop 3 end if 4 advance to next node 3 end if4 end loop

Print the result5 if (emptyStack(stack)) 1 print (there is no path to your goal) 6 else 1 print (The path to your goal is:) 2 loop (not emptyStack(stack)) 1 popStack(stack, pMap) 2 if (pMap not branchPoint) 1 print(pMap->nodeName) 3 end if 3 print (end of path)7 end if8 returnend seekGoal

Page 52: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

52西南财经大学天府学院

SummarySummary

A stack is a linear list in which all additions are restrict to one end, called the top. A stack is also called a LIFO list.A stack is a list in descending chronological sequence.We have defined eight operations for a stack:create stack, push stack, pop stack, stack top, empty stack, full stack, stack count, and destroy stack.Create stack initializes the stack metadata.Push adds an item to the top of the stack. After the push, the new item becomes the top.Each push must ensure that there is room for the new item. If there is no room, the stack is in an overflow state.Pop removes the item at the top of the stack. After the pop, the next item, if any, becomes the top.

Page 53: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

53西南财经大学天府学院

Summary(continue)Summary(continue)

Each pop must ensure that there is at least one item in the stack. If there is not at least one item. The stack is in an underflow state.The retrieve stack operation only copies the item at the top of the stack.Each retrieve must ensure that there is at least one item in the stack. If there is not at least one item. The stack is in an underflow state.Empty stack determines whether the stack is empty and returns a Boolean true if it is.Full stack determines whether there is room for at least one more item and returns a Boolean false if there is.Stack count returns the number of elements currently in the stack.Destroy stack releases all allocated data memory to dynamic memory.

Page 54: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

54西南财经大学天府学院

Summary(continue)Summary(continue)

One of the applications of a stack is reversing data. The nature of a stack (LIFO) allow us to push items into a stack and pop them in reverse order.Stacks are commonly used to parse data. We looked at an application to parse matching parenthesis in a source program.Stacks can be used to postpone the use of data. Whenever an action must be postponed. We can use a stack. Two applications were covered: Infix to postfix transformation and evaluation of postfix expressions.Stacks can be used to backtrack steps in a path. We looked at determining a path to a goal as an example of stack backtracking.

Page 55: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

55西南财经大学天府学院

ExerciseExercise

Imagine we have two empty stacks of integers, S1 and S2,draw a picture of each stack after the following operations:PushStack(S1,3);PushStack(S1,5);PushStack(S1,7);PushStack(S1,9);PushStack(S1,11);PuchStack(S1,13);while (! emptyStack(S1)){

popStack(S1,x);puchStack(S2,x);

}

Page 56: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

56西南财经大学天府学院

ExerciseExercise

Change the following infix expressions to postfix expression using the Stack:A*B+C*D (A+B)*C-D*F+CDetermine the value of the following postfix expression when the variables have the following values: A is 2, B is 3, C is 4, D is 5.AB*C-D+ ABC+*D-

Page 57: Data Structures( 数据结构 ) Course 4:Stack. 2 西南财经大学天府学院 Vocabulary Stack 堆栈 Stack Top 栈顶 Push stack 入栈 Pop stack 出栈 Overflow 上溢出 Underflow

57西南财经大学天府学院

HomeworkHomework

Write a program that simulate a mouse in a maze, the program must print the path taken by the mouse form the start point to the final point.the maze as follow(0 means can use by mouse,1means can not use by mouse)

1 1 1 1 1 1 1 1 1 1 1 start 0 0 0 1 1 0 1 0 1 0 1

1 1 0 1 0 0 0 0 0 0 11 0 0 0 0 1 1 1 1 0 11 0 1 1 1 1 1 1 1 0 0 final

1 0 1 0 1 1 1 1 1 1 11 0 0 0 1 1 1 1 1 1 11 1 1 0 1 1 1 0 1 0 11 0 0 0 0 0 1 0 0 0 11 1 1 1 1 1 1 1 1 1 1


Recommended