1 / 91

Chapter 4

Chapter 4. Stacks. Basic stack operations Stack-linked-list implementation Stack applications Array implementation of stacks. Outline. A stack is a Last In, First Out (LIFO) data structure in which all insertions and deletion are restricted to one end called a top

tave
Télécharger la présentation

Chapter 4

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 4 Stacks

  2. Basic stack operations Stack-linked-list implementation Stack applications Array implementation of stacks Outline

  3. A stack is a Last In, First Out (LIFO) data structure in which all insertions and deletion are restricted to one end called a top When data are inserted into a stack and then they are removed, their order would be reversed Introduction

  4. Figure 4-1: Stacks

  5. There are 3 basic stack operations 1. push: adds an item at the top of the stack after the push, the new item becomes the top the stack is in an overflow state if there is no room for the new item 4-1 Basic Stack Operations

  6. Figure 4-2: Push stack operation

  7. 2. Pop when a stack is popped, the item at the top of the stack is removed and return it to the user as the top item has been removed, the next older item in the stack becomes the top when the last item in the stack is deleted, it must be set to its empty state if pop is called when the stack is empty, then it is in an underflow state Basic Stack Operations (2)

  8. Figure 4-3: Pop stack operation

  9. 3. Stack Top copies the item at the top of the stack it returns the data in the top element to the user but does not delete it stack top can also result in underflow if the stack is empty Basic Stack Operations (3)

  10. Figure 4-4: Stack top opertaion

  11. with an empty stack push green into stack push blue into stack pop push red into stack stack top =? pop pop An Example Figure 4-5

  12. Figure 4-5: Stack example

  13. There are several data structures that could be used to implement a stack, e.g. array or linked list In this section, we implement it as a linked list To implement the linked-list stack, we need two different structures a head node a data node 4-2 Stack-linked-list Implementation

  14. Figure 4-6: Conceptual and physical stack implementation

  15. stack head requires at least 2 attributes a count of the number of elements in the stack a top pointer other stack attributes can be placed in a stack head such as the time the stack was created stack datanode also requires at least 2 attributes data pointer to the next node Stack Head and Stack Data Node

  16. Figure 4-7: Stack data structure

  17. 8 operations are defined to solve any basic stack problem create stack - empty stack push stack - full stack pop stack - stack count stack top - destroy stack there may be additional stack operations Stack Algorithms

  18. Figure 4-8, Part I: Linked list stack operations

  19. Figure 4-8, Part II: Linked list stack operations

  20. algorithm createStack Allocates memory for a stack head node from dynamic memory and returns its address to the caller. Pre Nothing Post Head node allocated or error returned Return pointer to head node or null pointer if no memory 1.Create stack

  21. Algorithm createStack Allocates memory for a stack head node from dynamic memory and returns its address to the caller. Pre Nothing Post Head node allocate or error returned Return pointer to head node or null pointer if no memory 1 if (memory available) 1 allocate (stackPtr) 2 stackPtr->count = 0; 3 stackPtr->top = null pointer 2 else 1 stackPtr = null pointer 3 return stackPtr end createStack Algorithm 4-1 Create stack

  22. algorithm pushStack (val stack <head pointer>, val inData <datatype>) Insert (push) one item into the stack. Pre stack is a pointer to the stack head structure data contains data to be pushed into Stack Post data have been pushed in stack Return returns true if successful; false if memory overflow 2. Push stack

  23. 1. allocate dynamic memory once the memory is allocated, 2. assign the data to the stack node 3. set the link to point to the node currently indicated as the stack top (pointer top) 4. update the stack top pointer (pointer next) 5. add one to the stack count Push stack (2)

  24. Figure 4-9: Push stack example

  25. algorithm pushStack (val stack <head pointer>, val data <dataType>) Insert (push) one item into the stack. Pre stack is a pointer to the stack head structure data contains data to be pushed into stack Post data heave been pushed in stack Return true if successful; false if memory overflow 1 if (stack 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 return success end pushStack Algorithm 4.2 Push stack

  26. algorithm popStack (val stack <head pointer>, ref dataOut <datatype> This algorithm pops the item on the top of the stack and returns it to the user. Pre stack is a pointer to the stack head structure dataOut is a reference variable to receive the data Post Data have been returned to calling algorithm Return true if data returned, false if underflow 3. Pop stack

  27. Figure 4-10: Pop stack

  28. Algotirhm popStack(val stack <head pointer>, ref dataOut <dataType>) This algorithm pops the item on the top of the stack and returns it to the user Pre stack is a pointer to the stack head structure DataOut is a reference variable to receive the data Post Data have been returned to calling algorithm Return true if successful; false if underflow 1 if (stack empty) 1 success = false 2 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 = true 3 return success end popStack Algorithm 4.3 Pop stack

  29. algorithm stackTop (val stack <head pointer>, ref dataOut <dataType>) This algorithm retrieves the data from the top of the stack without changing the stack without changing the stack. Pre stack is a pointer to the stack head structure Post Data have been returned to calling algorithm Return true if data returned, false if underflow 4. Stack top

  30. Algorithm stackTop ( val stack <head pointer>, ref dataOut <dataType>) This algorithm retrieves the data from the top if the stack without changing the stack Pre stack is a pointer to the stack head structure dataOut is a reference variable to receive the data Post Data have been returned to calling algorithm Return true if data returned, false if underflow 1 if (stack empty) 1 success = false 2 else 1 dataOut = stack->top->data 2 success = true 3 return success end stackTop Algorithm 4-4 Stack top

  31. algorithm emptyStack (val stack <head pointer>) Determines if stack is empty and return a boolean. Pre stack is a pointer to the stack head structure Post returns stack status Return boolean, true: stack empty, false: stack contains data 5. Empty stack

  32. Algorithm emptyStack (val stack <head pointer>) Determines if stack is empty and return a boolean. Pre stack is a pointer to the stack head structure Post returns stack status Return boolean, true: stack empty, false: stack contains data 1 if (stack not empty) 1 result = false 2 else 1 result = true 3 return result end emptyStack Algorithm 4-5 Empty stack

  33. algorithm fullStack (val stack <head pointer>) Determines if stack is empty and return a boolean. Pre stack is a pointer to the stack head structure Post returns stack status Return boolean, true: stack full, false: memory available 6. Full stack

  34. Algorithm fullStack (val stack <head pointer> Determines if stack is full and the stack head structure Pre stack is a pointer to the stack head structure Post returns stack status Return boolean, true: stack full, false: memory available 1 if (memory available) 1 result = false 2 else 1 result = true 3 return result end fullStack Algorithm 4-6 Full stack

  35. algorithm stackCount (val stack <head pointer>) Returns the number of elements currently in stack. Pre stack is a pointer to the stack head structure Post returns stack count Return integer 7. Stack count

  36. Algorithm stackCount (val stack <head pointer>) Returns the number of elements currently in stack. Pre stack is a pointer to the stack head structure Post returns stack count Return integer count of number of elements in stack 1 return (stack-> count) end stackCount Algorithm 4-7 Stack count

  37. algorithm destroyStack (val stack <head pointer>) This algorithm releases all nodes to dynamic memory. Pre stack is a pointer to the stack head structure Post stack empty and all nodes recycled Return null stack pointer 8. Destroy stack

  38. Algorithm destroyStack (val stack <head pointer>) This algorithm releases all nodes back to the dynamic memory. Pre stack is a pointer to the stack head structure Post stack empty and all nodes recycled Return null pointer 1 if (stack not empty) 1 loop ( stack->top not null) 1 temp = stack-> top 2 stack->top = stack ->top->link 3 recycle ( temp ) 2 recycle ( stack ) 3 return null pointer end destroyStack Algorithm 4-8 Destroy stack

  39. There are 4 common stack applications reversing data parsing data postponing data usage backtracking steps 4-3 Stack Applications

  40. given a set of data, the first and last elements are exchanged with all of the positions between the first and last being relatively exchanged also for example: {1, 2, 3, 4} becomes {4, 3, 2, 1} we examine 2 different reversing applications: reveres a list convert decimal to binary Reversing Data

  41. Algorithm reverseNumber This program reverses a list of integers read from the keyboard by pushing them into a stack and retrieving them one by one 1  stack = createStack 2  prompt (Enter a number) 3  read (number) Algorithm 4-9 Reverse a number series Fill stack 4  loop ( not end of data AND stack not full) 1 pushStack (number ) 2 prompt (Enter next number: <EOF> to stop) 3 read( number ) Print numbers in reverse 5  loop (not emptyStack (stack) 1 popStack (stack, dataOut) 2 print (dataOut) 6  stack = destroyStack (stack) end reverseNumber

  42. 1 read (number) 2 loop (number > 0) 1 digit = number modulo 2 2 print (digit) 3 number = number / 2 Convert Decimal to Binary

  43. algorithm decimalToBinary This algorithm reads an integer from the keyboard and print its binary equivalent. It uses a stack to reverse the order of 0’s and 1’s produces. 1 stack = createStack 2  prompt (Enter a decimal 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 creating digit) 2 quit algorithm 4 number = number/2 Algorithm 4-10 Convert decimal to binary

  44. Binary number create in stack. Now print it. 5  loop (not emptyStack(stack)) 1 popStack (stack,digit) 2 print(digit) Binary number create. Destroy stack and return 6 destroy(stack) end decimalToBinary Algorithm 4-10 Convert decimal to binary (2)

  45. any logic that breaks data into independent pieces for further processing for example, to translate a source program to machine language, a compiler must parse the program into individual parts such as keywords, names, and tokens one common programming problem, unmatched parentheses in an algebraic expression Parsing

  46. Figure 4-11: Unmatched parentheses examples

  47. algorithm parseParens This 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 (Error: closing parenthesis not matched) 2 else 1 popStack(stack,token) 2 if (not emptyStack(stack) 1 print (Error : opening parenthesis not matched) end parseParens Algorithm 4-11 Parse parentheses

  48. When we used a stack to reverse a list, the entire list was read before we began outputting the results Often the logic of an application requires that the usage of data be deferred until some later point A stack can be useful when the application requires that data’s use be postponed for a while two stack postponement applications: infix to postfix translation postfix expression evaluation Postponement

  49. An arithmetic expression can be represented in 3 different formats infix: the operator comes between the 2 operands postfix: the operator comes after the 2 operands prefix: the operator comes before the 2 operands Infix: a + b Postfix: a b + Prefix: + a b 1. Infix To Postfix Transformation

  50. Add parentheses using the arithmetic precedence: multiply and divide before add and subtract Moving the operator to the location of the expression’s closing parentheses Remove all parentheses Manual Transformation from Infix to Postfix

More Related