1 / 83

Stack and Queue

Stack and Queue. Stack. Definition. Stack is an ordered collection of data items in which access is possible only at one end (called the top of the stack). Stacks are known as LIFO (Last In, First Out) lists. The last element inserted will be the first to be retrieved.

elani
Télécharger la présentation

Stack and Queue

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. Stack and Queue

  2. Stack

  3. Definition • Stack is an ordered collection of data items in which access is possible only at one end (called the top of the stack). • Stacks are known as LIFO (Last In, First Out) lists. The last element inserted will be the first to be retrieved

  4. Stack as an AbstractData Type Basic operations: 1. Construct a stack (usually empty) 2. Check if stack is empty 3. Push: Add an element at the top of the stack 4. Pop: Remove the top element of the stack 5. Peek: Retrieve the top element of the stack Adding a plate pushes those below it down in the stack Removing a plate pops those below it up one position.

  5. top A A B A top top Push and Pop • Primary operations: Push and Pop • Push • Add an element to the top of the stack • Pop • Remove the element at the top of the stack empty stack push an element push another pop top

  6. Implementation of Stacks • Any list implementation could be used to implement a stack • Arrays (static: the size of stack is given initially) • Linked lists (dynamic: never become full) • We will explore implementations based on array and linked list

  7. Array Implementation • Need to declare an array size ahead of time • Associated with each stack is TopOfStack • for an empty stack, set TopOfStack to -1 • Push • (1)   Increment TopOfStack by 1. • (2)   Set Stack[TopOfStack] = X • Pop • (1)   Set return value to Stack[TopOfStack] • (2)   Decrement TopOfStack by 1 • These operations are performed in very fast constant time

  8. Stack class class Stack { public: Stack(int size = 10); // constructor boolIsEmpty() { return top == -1; } boolIsFull() { return top == maxSize; } double Peek(); void push(const double x); double pop(); void displayStack(); private: intmaxSize // max stack size = size - 1 int top; // current top of stack double[] values; // element array };

  9. Stack class • Attributes of Stack • maxTop: the max size of stack • top: the index of the top element of stack • values: point to an array which stores elements of stack • Operations of Stack • IsEmpty: return true if stack is empty, return false otherwise • IsFull: return true if stack is full, return false otherwise • Peek: return the element at the top of stack • Push: add an element to the top of stack • Pop: delete the element at the top of stack • DisplayStack: print all the data in the stack

  10. Create Stack • The constructor of Stack • Allocate a stack array of size. By default, size = 10. • When the stack is full, top will have its maximum value, i.e. size – 1. • Initially top is set to -1. It means the stack is empty. Stack(int size) { maxTop = size - 1; values = new double[size]; top = -1; } Although the constructor dynamically allocates the stack array, the stack is still static. The size is fixed after the initialization.

  11. Push Stack • void Push(const double x); • Push an element onto the stack • If the stack is full, print the error information. • Note top always represents the index of the top element. After pushing an element, increment top. void push(double x) { if (IsFull()) System.out.println("Error: the stack is full.“); else values[++top] = x; }

  12. Pop Stack • double Pop() • Pop and return the element at the top of the stack • If the stack is empty, print the error information. (In this case, the return value is useless.) • Don’t forgot to decrement top double pop() throw EmptyStackException{ if (IsEmpty()) { System.out.println("Error: the stack is empty.“); throw EmptyStackException; } else { return values[top--]; } }

  13. Stack Top • double Peek() • Return the top element of the stack • Unlike Pop, this function does not remove the top element double Peek() throws EmptyStackException{ if (IsEmpty()) { System.out.println("Error: the stack is empty." ); throw EmptyStackException; } else return values[top]; }

  14. Printing all the elements • void DisplayStack() • Print all the elements void DisplayStack() { System.out.print("top -->“); for (inti = top; i >= 0; i--) System.out.print( "\t|\t" +values[i] +"\t|\n“); System.out.println("\t|---------------|“);} }

  15. Using Stack result Initialize stack with 5 items push(5.0); push(6.5); push(-3.0); push(-8.0); DisplayStack(); pop(); then print top(); pop(); then print top();

  16. Stack: Linked List Implementation • Push and pop at the head of the list • New nodes should be inserted at the front of the list, so that they become the top of the stack • Nodes are removed from the front (top) of the list • Straight-forward linked list implementation • push and pop can be implemented fairly easily, e.g. assuming that head is a reference to the node at the front of the list

  17. 6 List Stack Example Java Code Stack st = new Stack(); st.push(6); top

  18. 6 1 List Stack Example Java Code Stack st = new Stack(); st.push(6); st.push(1); top

  19. 6 1 7 List Stack Example Java Code Stack st = new Stack(); st.push(6); st.push(1); st.push(7); top

  20. 6 1 7 8 List Stack Example Stack st = new Stack(); st.push(6); st.push(1); st.push(7); st.push(8); top

  21. 6 1 7 8 List Stack Example Java Code Stack st = new Stack(); st.push(6); st.push(1); st.push(7); st.push(8); st.pop(); top

  22. 6 1 7 List Stack Example Java Code Stack st = new Stack(); st.push(6); st.push(1); st.push(7); st.push(8); st.pop(); top

  23. Stack: ADT List Implementation • Push() and pop() either at the beginning or at the end of ADT List • at the beginning:publicvoid push(Object newItem) { list.insertAtHead(item); } // end push public Object pop() { return list.removeFromHead(); } // end pop

  24. Java implementation of StackSpecification of the Stack Abstract Data Type (continued) Chapter 5: Stacks

  25. Stack Applications • Text studies two client programs using stacks • Palindrome finder • Parentheses matcher • A Palindrome is a string that reads the same in either direction • Examples: “Able was I ere I saw Elba” Chapter 5: Stacks

  26. Stack Applications (continued) Chapter 5: Stacks

  27. Stack Applications (continued) • When analyzing arithmetic expressions, it is important to determine whether an expression is balanced with respect to parentheses • (a+b*(c/(d-e)))+(d/e) • Problem is further complicated if braces or brackets are used in conjunction with parenthesis • Solution is to use stacks! Chapter 5: Stacks

  28. Stack Applications (continued) Chapter 5: Stacks

  29. Stack Applications (continued) Chapter 5: Stacks

  30. Implementing a Stack with a List Component • Can use either the ArrayList, Vector, or the LinkedList classes as all implement the List interface • Name of class illustrated in text is ListStack • ListStack is an adapter class as it adapts the methods available in another class to the interface its clients expect by giving different names to essentially the same operations Chapter 5: Stacks

  31. Implementing a Stack Using an Array • Need to allocate storage for an array with an initial default capacity when creating a new stack object • Need to keep track of the top of the stack • No size method Chapter 5: Stacks

  32. Implementing a Stack Using an Array (continued) Chapter 5: Stacks

  33. Implementing a Stack as a Linked Data Structure • We can implement a stack using a linked list of nodes Chapter 5: Stacks

  34. Comparison of Stack Implementations • Vector is poor choice for stack implementation as all Vector methods are accessible • Easiest implementation would be to use an ArrayList component for storing data • All insertions and deletions are constant time regardless of the type of implementation discussed • All insertions and deletions occur at one end Chapter 5: Stacks

  35. Additional Stack Applications • Consider two case studies that relate to evaluating arithmetic expressions • Postfix and infix notation • Expressions normally written in infix form • Binary operations inserted between their operands • A computer normally scans an expression string in the order that it is input; easier to evaluate an expression in postfix form Chapter 5: Stacks

  36. Additional Stack Applications (continued) Chapter 5: Stacks

  37. Additional Stack Applications (continued) • Advantage of postfix form is that there is no need to group subexpressions in parentheses • No need to consider operator precedence

  38. Evaluating Postfix Expressions

  39. Evaluating Postfix Expressions (continued)

  40. Evaluating Postfix Expressions (continued) Chapter 5: Stacks

  41. Evaluating Postfix Expressions (continued) Chapter 5: Stacks

  42. Converting from Infix to Postfix Chapter 5: Stacks

  43. Additional Stack Applications (continued)

  44. Evaluating Postfix Expressions (continued)

  45. Evaluating Postfix Expressions (continued)

  46. Queue

  47. Queue Overview • Queue ADT • Basic operations of queue • Enqueuing, dequeuing. • Implementation of queue • Array • Linked list

  48. Queue ADT • Like a stack, a queue is also a list. However, with a queue, insertion is done at one end, while deletion is performed at the other end. • Accessing the elements of queues follows a First In, First Out (FIFO) order. • Like customers standing in a check-out line in a store, the first customer in is the first customer served.

  49. The Queue ADT • Another form of restricted list • Insertion is done at one end, whereas deletion is performed at the other end • Basic operations: • enqueue: insert an element at the rear of the list • dequeue: delete the element at the front of the list • First-in First-out (FIFO) list

  50. Enqueue and Dequeue • Primary queue operations: Enqueue and Dequeue • Like check-out lines in a store, a queue has a front and a rear. • Enqueue • Insert an element at the rear of the queue • Dequeue • Remove an element from the front of the queue Remove(Dequeue) Insert (Enqueue) front rear

More Related