Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 17: Stacks and Queues Java Programming: Program Design Including Data Structures Program Design Including Data Structures.

Similar presentations


Presentation on theme: "Chapter 17: Stacks and Queues Java Programming: Program Design Including Data Structures Program Design Including Data Structures."— Presentation transcript:

1 Chapter 17: Stacks and Queues Java Programming: Program Design Including Data Structures Program Design Including Data Structures

2 Java Programming: Program Design Including Data Structures2 Chapter Objectives  Learn about stacks  Examine various stack operations  Learn how to implement a stack as an array  Learn how to implement a stack as a linked list  Discover stack applications

3 Java Programming: Program Design Including Data Structures3 Chapter Objectives (continued)  Learn how to use a stack to remove recursion  Learn about queues  Examine various queue operations  Learn how to implement a queue as an array  Discover queue applications

4 Java Programming: Program Design Including Data Structures4 Stacks  Lists of homogeneous elements  Addition and deletion of elements occur only at one end, called the top of the stack  Computers use stacks to implement method calls  Stacks are also used to convert recursive algorithms into nonrecursive algorithms  Especially recursive algorithms that are not tail recursive

5 Java Programming: Program Design Including Data Structures5 Stacks (continued) Figure 17-1 Various types of stacks

6 Java Programming: Program Design Including Data Structures6 Stacks (continued)  Stacks are also called Last Input First Output (LIFO) data structures  Operations performed on stacks  Push: adds an element to the stack  Pop: removes an element from the stack  Peek: looks at the top element of the stack

7 Java Programming: Program Design Including Data Structures7 Stacks (continued) Figure 17-3 Stack operations

8 Java Programming: Program Design Including Data Structures8 Stacks (continued) Figure 17-4 UML diagram of the interface StackADT

9 Java Programming: Program Design Including Data Structures9 StackException Class  Adding an element to a full stack and removing an element from an empty stack would generate errors or exceptions  Stack overflow exception  Stack underflow exception  Classes that handle these exceptions  StackException extends RunTimeException  StackOverflowException extends StackException  StackUnderflowException extends StackException

10 Java Programming: Program Design Including Data Structures10 Implementation of Stacks as Arrays  The array implementing a stack is an array of reference variables  Each element of the stack can be assigned to an array slot  The top of the stack is the index of the last element added to the stack  To keep track of the top position, declare a variable called stackTop

11 Java Programming: Program Design Including Data Structures11 Implementation of Stacks as Arrays (continued) Figure 17-5 UML class diagram of the class StackClass

12 Java Programming: Program Design Including Data Structures12 Implementation of Stacks as Arrays (continued) Figure 17-6 Example of a stack

13 Java Programming: Program Design Including Data Structures13 Constructors  Default constructor public StackClass() { maxStackSize = 100; stackTop = 0; //set stackTop to 0 list = (T[]) new Object[maxStackSize]; //create the array }//end default constructor

14 Java Programming: Program Design Including Data Structures14 Initialize Stack  Method initializeStack public void initializeStack() { for (int i = 0; i < stackTop; i++) list[i] = null; stackTop = 0; }//end initializeStack

15 Java Programming: Program Design Including Data Structures15 Empty Stack  Method isEmptyStack public boolean isEmptyStack() { return (stackTop == 0); }//end isEmptyStack

16 Java Programming: Program Design Including Data Structures16 Full Stack  Method isFullStack public boolean isFullStack() { return (stackTop == maxStackSize); }//end isFullStack

17 Java Programming: Program Design Including Data Structures17 Push  Method push public void push(T newItem) throws StackOverflowException { if (isFullStack()) throw new StackOverflowException(); list[stackTop] = newItem; //add newItem at the //top of the stack stackTop++; //increment stackTop }//end push

18 Java Programming: Program Design Including Data Structures18 Peek  Method peek public T peek() throws StackUnderflowException { if (isEmptyStack()) throw new StackUnderflowException(); return (T) list[stackTop - 1]; }//end peek

19 Java Programming: Program Design Including Data Structures19 Pop  Method pop public void pop() throws StackUnderflowException { if (isEmptyStack()) throw new StackUnderflowException(); stackTop--; //decrement stackTop list[stackTop] = null; }//end pop

20 Java Programming: Program Design Including Data Structures20 Programming Example: Highest GPA  Program reads a data file consisting of  Each student’s GPA followed by the student’s name  Then it prints  Highest GPA  The names of all the students with that GPA  The program uses a stack to keep track of the highest GPA

21 Java Programming: Program Design Including Data Structures21 Linked Implementation of Stacks  Arrays have fixed sizes  Only a fixed number of elements can be pushed onto the stack  Dynamically allocate memory using reference variables  Implement a stack dynamically  Similar to the array representation, stackTop is used to locate the top element  stackTop is now a reference variable

22 Java Programming: Program Design Including Data Structures22 Linked Implementation of Stacks (continued) Figure 17-13 Nonempty linked stack

23 Java Programming: Program Design Including Data Structures23 Default Constructor  Default constructor public LinkedStackClass() { stackTop = null; }//end constructor

24 Java Programming: Program Design Including Data Structures24 Initialize Stack  Method initializeStack public void initializeStack() { stackTop = null; }//end initializeStack

25 Java Programming: Program Design Including Data Structures25 Empty Stack and Full Stack  Methods isEmptyStack and isFullStack public boolean isEmptyStack() { return (stackTop == null); }//end isEmptyStack public boolean isFullStack() { return false; }//end isFullStack

26 Java Programming: Program Design Including Data Structures26 Push  Method push public void push(T newElement) { StackNode newNode; //reference variable to create //the new node newNode = new StackNode (newElement, stackTop); //create //newNode and insert //before stackTop stackTop = newNode; //set stackTop to point to //the top element } //end push

27 Java Programming: Program Design Including Data Structures27 Peek  Method peek public T peek() throws StackUnderflowException { if (stackTop == null) throw new StackUnderflowException(); return stackTop.info; }//end top

28 Java Programming: Program Design Including Data Structures28 Pop  Method pop public void pop() throws StackUnderflowException { if (stackTop == null) throw new StackUnderflowException(); stackTop = stackTop.link; //advance stackTop to the //next node }//end pop

29 Java Programming: Program Design Including Data Structures29 Stack as Derived from the class UnorderedLinkedList  The class LinkedStackClass can be derived from the class LinkedListClass  The class LinkedListClass is an abstract class  You can derive the class LinkedStackClass from the class UnorderedLinkedList

30 Java Programming: Program Design Including Data Structures30 Applications of Stacks: Postfix Expression Calculator  Infix notation  The operator is written between the operands  Prefix or Polish notation  Operators are written before the operands  Does not require parentheses  Reverse Polish or postfix notation  Operators follow the operands  Has the advantage that the operators appear in the order required for computation

31 Java Programming: Program Design Including Data Structures31 Applications of Stacks: Postfix Expression Calculator (continued) Table 17-1 Infix expressions and their equivalent postfix expressions

32 Java Programming: Program Design Including Data Structures32 Applications of Stacks: Postfix Expression Calculator (continued)  Algorithm to evaluate postfix expressions  Scan the expression from left to right  When an operator is found, back up to get the required number of operands  Perform the operation  Continue processing the expression

33 Java Programming: Program Design Including Data Structures33 Main Algorithm  Main algorithm in pseudocode for processing a postfix expression Get the next expression while more data to process { a. initialize the stack b. process the expression c. output result d. get the next expression }

34 Java Programming: Program Design Including Data Structures34 Method evaluateExpression  General algorithm for evaluateExpression get the next token while (token != '=') { if (token is a number) { output number push number into stack } else { token is an operation call method evaluateOpr to evaluate the operation } if (no error in the expression) get next token else discard the expression }

35 Java Programming: Program Design Including Data Structures35 Method evaluateOpr  This method evaluates an operation  Two operands are needed to evaluate an operation  Operands are stored in the stack  The stack must contain at least two operands  Otherwise, the operation cannot be evaluated

36 Java Programming: Program Design Including Data Structures36 Method printResult public static void printResult(StackClass pStack, PrintWriter outp) { Double result; Double temp; if (expressionOk) //if no error, print the result { if (!pStack.isEmptyStack()) { result = (Double) pStack.peek(); pStack.pop(); if (pStack.isEmptyStack()) outp.printf(“%s %.2f %n”, strToken, result); else outp.println(strToken + “ (Error: Too many operands)”); }//end if else outp.println(“ (Error in the expression)”); } else outp.println(“ (Error in the expression)”); outp.println(“_________________________________”); }//end printResult

37 Java Programming: Program Design Including Data Structures37 Postfix Expression Calculator: Graphical User Interface (GUI) Figure 17-28 GUI for the postfix calculator

38 Java Programming: Program Design Including Data Structures38 Postfix Expression Calculator: Graphical User Interface (GUI) (continued)  Methods evaluateExpression, evaluateOpr, and printResult need minor modifications  The data are no longer coming from a file  The output is no longer stored in a file  To simplify the accessing of the stack  Declare it as an instance variable of the class containing the GUI program

39 Java Programming: Program Design Including Data Structures39 Postfix Expression Calculator: Graphical User Interface (GUI) (continued)  To create the GUI, the class containing the GUI must extend the class JFrame  The GUI interface contains several labels, three buttons, and a textfield  When the user clicks a button, it should generate an action event  You need to handle this event  The class constructor creates the GUI components and initialize them

40 Java Programming: Program Design Including Data Structures40 Postfix Expression Calculator: Graphical User Interface (GUI) (continued) Figure 17-29 Sample run of PostfixCalculator program

41 Java Programming: Program Design Including Data Structures41 Removing Recursion: Nonrecursive Algorithm to Print a Linked List Backward  Naïve approach  Get the last node of the list and print it  Traverse the link starting at the first node  Repeat this process for every node  Traverse the link starting at the first node until you reach the desired node  Very inefficient

42 Java Programming: Program Design Including Data Structures42 Removing Recursion: Nonrecursive Algorithm to Print a Linked List Backward (continued) current = first; //Line 1 while (current != null) //Line 2 { stack.push(current); //Line 3 current = current.link; //Line 4 }

43 Java Programming: Program Design Including Data Structures43 Removing Recursion: Nonrecursive Algorithm to Print a Linked List Backward (continued) Figure 17-36 List and stack after the staments stack.push(current); and current = current.link; executes

44 Java Programming: Program Design Including Data Structures44 The class Stack Table 17-2 Members of the class Stack

45 Java Programming: Program Design Including Data Structures45 Queues  Data structure in which the elements are added at one end, called the rear, and deleted from the other end, called the front  A queue is a First In First Out data structure  As in a stack, the middle elements of the queue are inaccessible

46 Java Programming: Program Design Including Data Structures46 Queue Operations  Queue operations  initializeQueue  isEmptyQueue  isFullQueue  front  back  addQueue  deleteQueue

47 Java Programming: Program Design Including Data Structures47 QueueException Class  Adding an element to a full queue and removing an element from an empty queue would generate errors or exceptions  Queue overflow exception  Queue underflow exception  Classes that handle these exceptions  QueueException extends RunTimeException  QueueOverflowException extends QueueException  QueueUnderflowException extends QueueException

48 Java Programming: Program Design Including Data Structures48 Implementation of Queues as Arrays  Instance variables  An array to store the queue elements  queueFront: keeps track of the first element  queueRear: keeps track of the last element  maxQueueSize : specifies the maximum size of the queues

49 Java Programming: Program Design Including Data Structures49 Implementation of Queues as Arrays (continued) Figure 17-42 Queue after two more addQueue operations

50 Java Programming: Program Design Including Data Structures50 Implementation of Queues as Arrays (continued) Figure 17-43 Queue after the deleteQueue operation

51 Java Programming: Program Design Including Data Structures51 Implementation of Queues as Arrays (continued)  Problems with this implementation  Arrays have fixed sizes  After various insertion and deletion operations, queueRear will point to the last array position  Giving the impression that the queue is full  Solutions  Slide all of the queue elements toward the first array position  Use a circular array

52 Java Programming: Program Design Including Data Structures52 Implementation of Queues as Arrays (continued) Figure 17-45 Circular queue

53 Java Programming: Program Design Including Data Structures53 Implementation of Queues as Arrays (continued) Figure 17-46 Queue with two elements at positions 98 and 99

54 Java Programming: Program Design Including Data Structures54 Implementation of Queues as Arrays (continued) Figure 17-47 Queue after one more addQueue operation

55 Java Programming: Program Design Including Data Structures55 Constructors  Default constructor //Default constructor public QueueClass() { maxQueueSize = 100; queueFront = 0; //initialize queueFront queueRear = maxQueueSize - 1; //initialize queueRear count = 0; list = (T[]) new Object[maxQueueSize]; //create the //array to implement the queue }

56 Java Programming: Program Design Including Data Structures56 initializeQueue  Method initilializeQueue public void initializeQueue() { for (int i = queueFront; i < queueRear; i = (i + 1) % maxQueueSize) list[i] = null; queueFront = 0; queueRear = maxQueueSize - 1; count = 0; }

57 Java Programming: Program Design Including Data Structures57 Empty Queue and Full Queue  Methods isEmptyQueue and isFullQueue public boolean isEmptyQueue() { return (count == 0); } public boolean isFullQueue() { return (count == maxQueueSize); }

58 Java Programming: Program Design Including Data Structures58 Front  Method front public T front() throws QueueUnderflowException { if (isEmptyQueue()) throw new QueueUnderflowException(); return (T) list[queueFront]; }

59 Java Programming: Program Design Including Data Structures59 Back  Method back public T back() throws QueueUnderflowException { if (isEmptyQueue()) throw new QueueUnderflowException(); return (T) list[queueRear]; }

60 Java Programming: Program Design Including Data Structures60 addQueue  Method addQueue public void addQueue(T queueElement) throws QueueOverflowException { if (isFullQueue()) throw new QueueOverflowException(); queueRear = (queueRear + 1) % maxQueueSize; //use the //mod operator to advance queueRear //because the array is circular count++; list[queueRear] = queueElement; }

61 Java Programming: Program Design Including Data Structures61 deleteQueue  Method deleteQueue public void deleteQueue() throws QueueUnderflowException { if (isEmptyQueue()) throw new QueueUnderflowException(); count--; list[queueFront] = null; queueFront = (queueFront + 1) % maxQueueSize; //use the //mod operator to advance queueFront //because the array is circular }

62 Java Programming: Program Design Including Data Structures62 Linked Implementation of Queues  Simplifies many of the special cases of the array implementation  Because the memory to store a queue element is allocated dynamically, the queue is never full  Class LinkedQueueClass implements a queue as a linked data structure  It uses nodes of type QueueNode

63 Java Programming: Program Design Including Data Structures63 Linked Implementation of Queues (continued)  Method initializeQueue public void initializeQueue() { queueFront = null; queueRear = null; }

64 Java Programming: Program Design Including Data Structures64 Linked Implementation of Queues (continued)  Methods isEmptyQueue and isFullQueue public boolean isEmptyQueue() { return (queueFront == null); } public boolean isFullQueue() { return false; }

65 Java Programming: Program Design Including Data Structures65 addQueue  Method addQueue public void addQueue(T newElement) { QueueNode newNode; newNode = new QueueNode (newElement, null); //create //newNode and assign newElement to newNode if (queueFront == null) //if initially the queue is empty { queueFront = newNode; queueRear = newNode; } else //add newNode at the end { queueRear.link = newNode; queueRear = queueRear.link; } }//end addQueue

66 Java Programming: Program Design Including Data Structures66 front and back  Methods front and back public T front() throws QueueUnderflowException { if (isEmptyQueue()) throw new QueueUnderflowException(); return queueFront.info; } public T back() throws QueueUnderflowException { if (isEmptyQueue()) throw new QueueUnderflowException(); return queueRear.info; }

67 Java Programming: Program Design Including Data Structures67 deleteQueue  Method deleteQueue public void deleteQueue() throws QueueUnderflowException { if (isEmptyQueue()) throw new QueueUnderflowException(); queueFront = queueFront.link; //advance queueFront if (queueFront == null) //if after deletion the queue queueRear = null; //is empty, set queueRear to null } //end deleteQueue

68 Java Programming: Program Design Including Data Structures68 Queue Derived from the class UnorderedLinkedList  The class LinkedQueueClass can be derived from the class UnorderedLinkedListClass  addQueue is similar to insertFirst  Likewise, the operations initializeQueue, initializeList, isEmptyQueue, and isEmptyList are similar  queueFront is the same as first  queueRear is the same as last

69 Java Programming: Program Design Including Data Structures69 Application of Queues: Simulation  Simulation  A technique in which one system models the behavior of another system  Used when it is too expensive or dangerous to experiment with real systems  You can also design computer models to study the behavior of real systems  Queuing systems  Queues of objects are waiting to be served

70 Java Programming: Program Design Including Data Structures70 Designing a Queuing System  Terms  Server  Object that provides a service  Customer  Object receiving a service  Transaction time  The time it takes to serve a customer

71 Java Programming: Program Design Including Data Structures71 Designing a Queuing System (continued)  Components  List of servers  Queue of waiting objects  Process  The customer at the front of the queue waits for the next available server  When a server becomes free, the customer at the front of the queue moves to be served  At the beginning, all servers are free

72 Java Programming: Program Design Including Data Structures72 Designing a Queuing System (continued)  What you need to know  The number of servers  The customer expected arrival time  The time between the arrivals of customers  The number of events affecting the system  Time-driven simulation  Uses a clock that can be implemented as a counter  The simulation is run for a fixed amount of time

73 Java Programming: Program Design Including Data Structures73 Customer Figure 17-54 UML class diagram of the class Customer

74 Java Programming: Program Design Including Data Structures74 Customer (continued)  Methods getWaitingTime and incrementWaitingTime public int getWaitingTime() { return waitingTime; } public void incrementWaitingTime() { waitingTime++; }

75 Java Programming: Program Design Including Data Structures75 Server Figure 17-55 UML class diagram of the class Server

76 Java Programming: Program Design Including Data Structures76 Server (continued)  Methods setTransactionTime and decreaseTransactionTime public void setTransactionTime(int t) { transactionTime = t; } public void setTransactionTime() { transactionTime = currentCustomer.getTransactionTime(); } public void decreaseTransactionTime() { transactionTime--; }

77 Java Programming: Program Design Including Data Structures77 Server List Figure 17-56 UML class diagram of the class serverList

78 Java Programming: Program Design Including Data Structures78 Server List (continued)  Method setServerBusy public void setServerBusy(int serverID, Customer cCustomer, int tTime) { servers[serverID].setBusy(); servers[serverID].setTransactionTime(tTime); servers[serverID].setCurrentCustomer(cCustomer); } public void setServerBusy(int serverID, Customer cCustomer) { int time; time = cCustomer.getTransactionTime(); servers[serverID].setBusy(); servers[serverID].setTransactionTime(time); servers[serverID].setCurrentCustomer(cCustomer); }

79 Java Programming: Program Design Including Data Structures79 Waiting Customer Queue  Class WaitingCustomerQueue class WaitingCustomerQueue extends QueueClass { public WaitingCustomerQueue() { super(); } public WaitingCustomerQueue(int size) { super(size); } public void updateWaitingQueue() { //... }

80 Java Programming: Program Design Including Data Structures80 Main Program  To run the simulation, you need the following simulation parameters  Number of time units the simulation should run  Number of servers  Amount of time it takes to serve a customer  Transaction time  Approximate time between customer arrivals

81 Java Programming: Program Design Including Data Structures81 Main Program (continued)  General algorithm  Declare and initialize the variables, including the simulation parameters  Run the main loop that moves customers from waiting queue to the next available server and updates simulation times  Customer waiting time  Server busy time  Print the appropriate results

82 Java Programming: Program Design Including Data Structures82 Chapter Summary  Stacks  Addition and deletion of elements occur only at one end, called the top of the stack  Follow a LIFO policy  Stack implementation  Array-based stacks  Linked stacks  Stacks are used to convert recursive algorithms into nonrecursive algorithms

83 Java Programming: Program Design Including Data Structures83 Chapter Summary (continued)  Queues  Elements are added at one end, called the rear, and deleted from the other end, called the front  Follow a FIFO policy  Queue implementation  Array-based queues  Linked queues  Queues are used to construct computer-aided simulation programs


Download ppt "Chapter 17: Stacks and Queues Java Programming: Program Design Including Data Structures Program Design Including Data Structures."

Similar presentations


Ads by Google