1 / 53

Introduction to Data Structures

Introduction to Data Structures. CHAPTER 3 STACKS and QUEUES. 3.1 The Stack Abstract Data Type 3.2 The Queue Abstract Data Type 3.3 A Mazing Problem 3.4 Evaluation of Expressions 3.5 Multiple Stacks and Queues. Contents. Chapter 1 Basic Concepts Chapter 2 Arrays

ludwig
Download Presentation

Introduction to Data Structures

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. Introduction to Data Structures CHAPTER 3 STACKS and QUEUES 3.1 The Stack Abstract Data Type 3.2 The Queue Abstract Data Type 3.3 A Mazing Problem 3.4 Evaluation of Expressions 3.5 Multiple Stacks and Queues Chapter 3 Stacks and Queues

  2. Contents Chapter 1 Basic Concepts Chapter 2 Arrays Chapter 3 Stacks and Queues Chapter 4 Linked Lists Chapter 5 Trees Chapter 6 Graph Chapter 7 Sorting Chapter 8 Hashing Chapter 9 Heap Structures Chapter 10 Search Structures Chapter 3 Stacks and Queues

  3. 3.1 The Stack Abstract Data Type • Data Objects: • Ordered list or Linear list A = (a1, a2,..., an) n>0 ai is an element or atomsn=0 null, empty list • Stack • Queue Representing by - Array (ch. 2) - Linked (ch. 4) special cases of Ordered List Chapter 3 Stacks and Queues

  4. Basic Concepts: Stack • Stack: is an ordered list in which • all insertions and deletions are made at one end, called the top • Two operators: Push and Pop. top E D C B A S = (a0, ..., an-1) bottom top ai is on top of ai-1 LIFO (Last In First Out) Chapter 3 Stacks and Queues

  5. D C B A E D C B A B A C B A D C B A top top top top top A top Basic Concepts: Stack (cont.) • Stack: a Last-In-First-Out (LIFO) list Push (A) Push (B) Push (C) Push (D) Push (E) POP( ) = E Chapter 3 Stacks and Queues

  6. Basic Concepts: Stack Application • Example 3.1 [System Stack]: Stack Application • e.g. (Problem: process of subroutine calls) O.S proc. MAIN proc. A1 proc. A2 proc. A3 run MAIN call A1 call A2 call A3q: r:s: t: end Top/ CURRENT-ADDR Chapter 3 Stacks and Queues

  7. Stack Application: Function Call • An application of stack: stack frame of function call fp: a pointer to current stack frame local variables fp old frame pointer stack frame of invoking function a1 return address local variables (size?) local variables fp main old frame pointer old frame pointer return address Main return addr. System Stackafter A1 is invoked System StackbeforeA1 is invoked (a) (b) Chapter 3 Stacks and Queues

  8. Data Structure: Stack • Specification: • ADT3.1: Abstract data type Stack (p.104) • Objects • Specify - Define data member - Declare member functions • CreateS • Push (Add) • Pop (Delete) • IsFull • IsEmpty • Top top stack Chapter 3 Stacks and Queues

  9. Stack Operations • Operators on stack 1. CreateS(S): create S as an empty stack 2. Add(i, s): 3. Delete(S): 4. IsEmpty(S): top i  top Push(i,s) var←‵i′  top Pop(S) top true if S = empty → top = -1false 5. Top(S): return the top element of stack S 與 Pop不一樣 Top(S) top ‘i’ = Top(S) top Chapter 3 Stacks and Queues

  10. Stack ADT Specification structureStack is objects: a finite ordered list with zero or more elements.functions: for all stackStack, itemelement, max_stack_size  positive integerStack CreateS(max_stack_size) ::= create an empty stack whose maximum size is max_stack_size Boolean IsFull(stack, max_stack_size) ::= if (number of elements in stack == max_stack_size) returnTRUEelse returnFALSEStack Add(stack, item) ::=if (IsFull(stack)) stack_fullelse insert item into top of stack and returnBoolean IsEmpty(stack) ::= if(stack == CreateS(max_stack_size)) return TRUEelse returnFALSEElement Delete(stack) ::= if(IsEmpty(stack)) returnelse remove and return the item on the top of the stack. Chapter 3 Stacks and Queues

  11. Stack Implementation • Define data member • Representing a stack using 1-dim array • Stack CreateS(max_stack_size) ::= #define MAX_STACK_SIZE 100 typedef struct { int key; /*other fields */ } element; element stack[MAX_STACK_SIZE]; int top = -1; 0 1 2 n-1 top Chapter 3 Stacks and Queues

  12. if top = 99  full stack[99] . . . stack[2] stack[1] stack[0] top = -1  empty Stack Implementation (cont.) elementstack[100]; Chapter 3 Stacks and Queues

  13. Stack Implementation (cont.) • Stack functions • Boolean IsEmpty(Stack) ::= top == -1; • Boolean IsFull(Stack) ::= top >= MAX_STACK_SIZE-1; • Stack Add(stack, item) ::= void add(int *top, element item){ if (*top >= MAX_STACK_SIZE-1) { stack_full(); return; } stack[++*top] = item; } Push Garbage collection & Re-run top Chapter 3 Stacks and Queues

  14. Stack Implementation (cont.) • Stack Delete(stack, item) ::= void delete(int *top){ if (*top == -1) { return stack_empty(); return stack[(*top)--]; } Pop Chapter 3 Stacks and Queues

  15. Add Add front front rear rear Delete B C D E B C D A A B A B C A B C D front rear front rear Add Add front rear front rear 3.2 The Queue Abstract Data Type • Queue: a First-In-First-Out (FIFO) list Add Chapter 3 Stacks and Queues

  16. A B C D E front rear FIFO (First In First Out) Basic Concepts: Queue • Queue: is an ordered list in which • all insertions take place at one end, the rear, • all deletions take place at the other end, the front. Chapter 3 Stacks and Queues

  17. Basic Concepts: Queue Specification • Specification: • ADT3.2: Abstract data type Queue (p.107) • Objects • Specify - Define data member - Declare member functions 0 1 n-1 • CreateQ • IsFullQ • IsEmptyQ • AddQ • DeleteQ • FrontQ f = r = -1 Chapter 3 Stacks and Queues

  18. QUEUE ADT Specification structureQueue isobjects: a finite ordered list with zero or more elements.functions:for all queue Queue, item element, max_queue_size positive integerQueueCreateQ(max_queue_size) ::= create an empty queue whose maximum size is max_queue_sizeBoolean IsFullQ(queue, max_queue_size) ::= if (number of elements in queue == max_queue_size) return TRUE else return FALSEQueue AddQ(queue, item) ::= if (IsFullQ(queue)) queue_full else insert item at rear of queue and return queueBoolean IsEmptyQ(queue) ::= if (queue ==CreateQ(max_queue_size))return TRUE else return FALSE Element DeleteQ(queue) ::=if (IsEmptyQ(queue)) return else remove and return the item at front of queue. p.3-26 Chapter 3 Stacks and Queues

  19. Queue Implementation • Data member declaration: • By using 1-dimensional array • Queue CreateQ(max_queue_size) ::= • #define MAX_QUEUE_SIZE 100 • typedef struct { • int key; • /*other fields */ • } element; • element queue[MAX_QUEUE_SIZE]; • int rear = -1; • int front = -1; Chapter 3 Stacks and Queues

  20. Queue Implementation(cont.) elementqueue [100]; if rear = 99  full queue[99] . . . queue[2] queue[1] queue[0] front = rear = -1  empty Chapter 3 Stacks and Queues

  21. Queue Implementation(cont.) • Stack functions • Boolean IsEmptyQ(queue) ::= front == rear; • Boolean IsFullQ(queue) ::= rear == MAX_QUEUE_SIZE-1; • Queue AddQ(queue, item) ::= void addq(int *rear, element item){/* add an item to the queue */ if (*rear == MAX_QUEUE_SIZE_1) { queue_full( ); return; } queue[++*rear] = item;} Chapter 3 Stacks and Queues

  22. addq(&rear, 15); addq(&rear, 10); addq(&rear, 20); Queue Implementation(cont.) queue[99] . . . rear = 2 queue[2] 20 15 10 queue[1] queue[0] front = -1 Chapter 3 Stacks and Queues

  23. Queue Implementation(cont.) • Queue DeleteQ(queue) ::= element deleteq(int *front, int rear){ /* remove element at the front of the queue */ if ( *front == rear) return queue_empty( ); /* return an error key */ return queue[++ *front];} Chapter 3 Stacks and Queues

  24. Queue Implementation(cont.) queue[99] . . . rear = 2 queue[2] 20 15 queue[1] queue[0] front = 0 values = deleteq(&front, rear); 10 values = 10 Chapter 3 Stacks and Queues

  25. batch system job1 job2 multi programming OS job1 job2 Queue Application • Job Scheduling no prioritypriority 大 小or • operations1. CREATEQ (Q)2. ADDQ (i,Q) : add to the rear3. DELETEQ (Q) : removes the front element 4. FRONT (Q) : return the front element of Q 5. IsEmpty (Q) multi Queue 3.4 Front Rear Chapter 3 Stacks and Queues

  26. Queue Full Problem • (Solution 1) • (Solution 2)More efficient queue representation: by regarding the array Q(1:n) as Circular. Boolean IsFullQ(queue, max_queue_size ) ::= if (number of elements in queue == max_queue_size) return TRUE else return FALSE p.3-18 • Problem: there may be available space when IsFullQ is truei.e. may need some movements inserting Jobn+1   Jn+1 f=0 r=3 f=4 r=n f=3 r=n Chapter 3 Stacks and Queues

  27. Basic Concepts: Circular Queue • (Solution 2)Circular Queue • Q (0:n-1) • J1, J2, J3, J4 3 initial f = r = 0 f= r iff Circular Queue is empty 2 n-2 1 n-1 0 r f r Add: if r== n-1 then r = 0 else r = r+1  r = (r+1) mod n Delete if f== n-1 then f = 0 else f = f+1  f = (f+1) mod n J4 J3 J2 J1 n-1 0 f Chapter 3 Stacks and Queues

  28. 0 n-1 r f r Basic Concepts: Circular Queue • Note: AddQ r = (r+1) mod n if r == f then call QUEUE_FULL • Need to leave a space as unused • How to utilize the full space of circular queue • Using an additional tag tag = 0 iff Queue empty = 1 iff QUEUE_FULL • Note: testing needs time!! Slow down the algorithms. Chapter 3 Stacks and Queues

  29. void addq(int front, int *rear, element item){ /* add an item to the queue */ *rear = (*rear +1) % MAX_QUEUE_SIZE; if (front == *rear) queue_full(rear); /* reset rear and print error */ return; } queue[*rear] = item; } Circular Queue: Add • Add to a circular queue Chapter 3 Stacks and Queues

  30. [2] [3] J2 J3 J1 [1] [4] [0] [5] Circular Queue: Add (cont.) addq(front, &rear, ‘J1’); addq(front, &rear, ‘J2’); addq(front, &rear, ‘J3’); rear = 3 front = 0 Chapter 3 Stacks and Queues

  31. element deleteq(int* front, int rear){ element item; /* remove front element from the queue and put it in item */ if (*front == rear) return queue_empty( ); /* queue_empty returns an error key */ *front = (*front+1) % MAX_QUEUE_SIZE; return queue[*front];} Circular Queue: Delete • Delete from a circular queue Chapter 3 Stacks and Queues

  32. [2] [3] rear = 3 J2 J3 J1 [1] [4] front = 1 [0] [5] Circular Queue: Delete (cont.) values = deleteq(&front, rear); values = ‘J1’ Chapter 3 Stacks and Queues

  33. 3.3 A Mazing Problem:Stack Application • “Rat-in-a-maze” • Fig 3.8 Array MAZE [1..m,1..p] • 0: open path;1: barrier j entrance i exit Chapter 3 Stacks and Queues

  34. A Mazing Problem 0 1 0 0 0 1 1 0 0 0 1 1 1 1 1 1 0 0 0 1 1 0 1 1 1 0 0 1 1 1 0 1 1 00 0 0 1 1 1 1 0 0 1 1 1 1 0 1 1 1 1 0 1 1 0 1 1 0 0 1 1 0 1 0 0 1 0 1 1 1 1 1 1 1 0 0 1 1 0 1 1 1 0 1 0 0 1 0 1 0 1 1 1 1 0 0 1 1 1 1 1 1 1 1 0 0 1 1 0 1 1 0 1 1 1 1 1 0 1 1 1 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 0 0 1 0 0 1 1 1 1 1 0 1 1 1 1 0 Entrance Exit 1: blocked path 0: through path Chapter 3 Stacks and Queues

  35. A Mazing Problem • moves N(i-1, j) NN NE 2-dim array (i-1, j+1) (i-1, j-1) W (i, j-1) (i, j+1) E (i, j) (i+1, j-1) (i+1, j+1)SE SW (i+1, j)S • next step (g, h) g := i + move[d].vert h := j + move[d].horiz Chapter 3 Stacks and Queues

  36. A Mazing Problem Array MAZE [0..m+1, 0..p+1] MARK [0..m+1, 0..p+1] 0: not yet visited Chapter 3 Stacks and Queues

  37. 3.4 Evaluation of Expressions Example: X = a / b - c + d * e - a * c Let a = 4, b = c = 2, d = e = 3Evaluation 1: ((4/2)-2)+(3*3)-(4*2)=0 +9 - 8=1Evaluation 2:(4/(2-2+3))*(3-4)*2=(4/3)*(-1)*2=-2.66666… • How to generate the machine instructions corresponding to a given expression?  precedence rule + associative rule • “Machine” instructions T4  T1 - c T5  T4 + T2 X  T5 – T4 T1  a / b T2  d * e T3  a * c Chapter 3 Stacks and Queues

  38. Evaluation of Expressions: the Problem • Evaluation of expressions: Stack Application • Expression  Machine language (or Assembly code) • Evaluation • E.g. 1. Expression:X  A / B ** C + D * E – A * C (1) • a+b ab+ +abinfix postfix(suffix) prefix • ABC**/DE*+AC*- postfix of (1) 1 scanning 3次 21 22 23 31 32 Chapter 3 Stacks and Queues

  39. C B A B**C A E D A/B**C D*E A/B**C C A A/B**C+D*E A*C A/B**C+D*E A/B**C+D*E-A*C **  /  *  +  *  -  Stack Evaluation of Expressions: Example 1 • Example 1. • Infix: X  A / B ** C + D * E – A * C (1) • Postfix: ABC**/DE*+AC*- • Evaluate (1)  Evaluate postfix of (1) • Note: scan once Chapter 3 Stacks and Queues

  40. Evaluation of Expressions: Example 2 • Example 2. • Infix: A / B – C + D * E – A * C • Postfix: A B / C – D E * + A C * – • Figure 3.14: Postfix evaluation, p.120 • Operations vs. postfix • Ex. ??? • Program 3.9:Evaluating Postfix Expressions, p. 122 int eval(void) Chapter 3 Stacks and Queues

  41. Conversion: Infix  Postfix • Method 1 Rule (p.121) 1. Fully parenthesize the expression 2. Move all binary op. so that they replace their corresponding ‘)‘ 3. Delete all parentheses Example 1. A/B**C+E*D-A*C ((( A/(B**C))+(D*E))-(A*C))  ABC**/DE*+AC*- Example 2. A / B – C + D * E – A * C (Ex?) Chapter 3 Stacks and Queues

  42. output ABC**/DE*+AC*- ** / * + * - +  -  pop Conversion: Infix  Postfix (cont.) • Method 2: using stack Rule 1. operands  output; operators  Stack 2. Stack中,新priority > 於前者則 “疊上: push”  前者跳出。3. 最後,stack中之operator,pop出來。 • Example 1 A/B**C+E*D-A*C Ref. Fig 3.12 priority Chapter 3 Stacks and Queues

  43. output ABC+*D/ + ( * * / )  /  Conversion: Infix  Postfix (cont.) • Example 2 A*(B+C)/D rule 4: “(“及之後的op. 依序放入stack,遇到”)”時,一直 pop,直到pop出“(” • Example 3 (A*B)+C/D AB*CD/+ • Program 3.11: Infix  Postfix , p. 126 void postfix(void) Chapter 3 Stacks and Queues

  44. bottom top bottom top m[0] m[1] … m[n-2] m[n-1] bottommost bottommost stack 1 stack 2  bottom top top bottom 3.5 Multiple Stacks and Queues • coexist two variable-size stacks Note: STACK_FULL will occur only when the # of elements exceeds the total space Chapter 3 Stacks and Queues

  45. Coexist n Stacks • More than two Stacks, n • if the sizes are known  proportional distribution • unknown  equal segments 1 m m-1 0 m/n 2 m/n 3 m/n b(1) b(2) b(3) b(4) b(n) t(1) t(2) t(3) t(4) initial b(i) = t(i) = i m/n - 1, 0  i < n for stack i Chapter 3 Stacks and Queues

  46. Coexist n Stacks (cont.) • n Stacks: stack_1, stack_2, stack_3, stack_4, …, stack_n-1 • memory is divided into n equal segments • boundary[stack_no] • 0  stack_no < MAX_STACKS • top[stack_no] • 0  stack_no < MAX_STACKS Initially, boundary[i] = top[i]. -1 0 m/n 2 m/n m-1 m-1 … boundary[0] boundary[1] boundary[2] boundary[n] top[0] top[1] top[2] Chapter 3 Stacks and Queues

  47. #define MEMORY_SIZE 100 /* size of memory */#define MAX_STACK_SIZE 100 /* max number of stacks plus 1 *//* global memory declaration */element memory[MEMORY_SIZE];int top[MAX_STACKS];int boundary[MAX_STACKS];int n; /* number of stacks entered by the user */ Coexist n Stacks (cont.) Initialize stacks: top[0] = boundary[0] = -1;for (i = 1; i < n; i++) top[i] = boundary[i] = (MEMORY_SIZE/n) * i;boundary[n] = MEMORY_SIZE-1; Chapter 3 Stacks and Queues

  48. void add(int i, element item){ /* add an item to the ith stack */if (top[i] == boundary [i+1]) stack_full(i); memory[++top[i]] = item;}element delete(int i){ /* remove top element from the ith stack */if (top[i] == boundary[i])return stack_empty(i);return memory[top[i]--];} Coexist n Stacks: Add and Delete Chapter 3 Stacks and Queues

  49. Stack_i Full • Stack i meets Stack i+1, but the memory is not full Find j, stack i < j < n or 0  j < stack i such that top[j] < boundary[j+1] space b[0] t[0] b[1] t[1] b[i] t[i]t[i+1]t[j] b[j+1] b[n] b[i+1] shift stacks b[0] t[0] b[1] t[1] b[i] t[i]t[i+1]t[j] b[j+1] b[n] b[i+1] Chapter 3 Stacks and Queues

  50. shift stacks b[0] t[0] b[1] t[1] b[i] t[i]t[i+1]t[j] b[j+1] b[n] b[i+1] Stack_i Full (cont.) • If there is space available, it should shift stacks so that space is allocated to the full stack. space b[0] t[0] b[1] t[1] b[i] t[i]t[i+1]t[j] b[j+1] b[n] b[i+1] Chapter 3 Stacks and Queues

More Related