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.

Slides:



Advertisements
Similar presentations
Chapter 6 Queues and Deques.
Advertisements

Stack & Queues COP 3502.
Lec 7 Sept 17 Finish discussion of stack infix to postfix conversion Queue queue ADT implementation of insert, delete etc. an application of queue.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
Queue Overview Queue ADT Basic operations of queue
CHAPTER 4 Queues MIDTERM THURSDAY, OCTOBER 17 IN LAB.
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stack and Queue COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
Stacks Chapter 5. Chapter Objectives  To learn about the stack data type and how to use its four methods: push, pop, peek, and empty  To understand.
Queues Chapter 6. Chapter Objectives  To learn how to represent a waiting line (queue) and how to use the methods in the Queue interface for insertion.
CMPT 225 Stacks.
ITEC200 Week05 Stacks. 2 Learning Objectives – Week05 Stacks (Chapter05) Students can Use the methods provided in the public interface.
CHAPTER 3 Stacks. Chapter Objectives  To learn about the stack data type and how to use its four methods:  push  pop  peek  empty  To understand.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks Chapter 5. Chapter 5: Stacks2 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty.
Stacks and Queues COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
Stacks Chapter 5. Chapter 5: Stacks2 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Fall 2007CS 2251 Queues Chapter 6. Fall 2007CS 2252 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Stacks and Queues.
Queues Chapter 6. Chapter 6: Queues2 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in the Queue interface.
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.
Fall 2007CS 2251 Queues Chapter 6. Fall 2007CS 2252 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in.
Stacks and Queues. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor.
Lecture 11 Sept 26, 2011 Goals convert from infix to postfix.
Stacks, Queues, and Deques
Stacks, Queues, and Deques
Chapter 3 Stacks.
CHAPTER 3 Stacks MIDTERM OCTOBER 17 IN LAB. Chapter Objectives  To learn about the stack data type and how to use its four methods:  push  pop  peek.
Objectives of these slides:
COMP 121 Week 14: Queues. Objectives Learn how to represent a queue Learn how to use the methods in the Queue interface Understand how to implement the.
Comp 245 Data Structures Stacks. What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Lecture Objectives To understand how Java implements a stack To learn how to implement a stack using an underlying array or linked list Implement a simple.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
COMP 121 Week 13: Stacks. Objectives Learn about the stack data type and how to use its four methods: push, pop, peek, and empty Understand how Java implements.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
Fall 2007CS 2251 Queues Chapter 6. Fall 2007CS 2252 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in.
Queues Chapter 6. Chapter 6: Queues Chapter Objectives To learn how to represent a waiting line (queue) and how to use the five methods in the Queue interface:
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture6.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 18: Stacks and Queues.
Computer Science Department Data Structures and Algorithms Queues Lecture 5.
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
CSE 373: Data Structures and Algorithms Lecture 2: Queues.
Stacks & Queues. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy to use.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
Click to edit Master text styles Stacks Data Structure.
Review Array Array Elements Accessing array elements
Stacks Chapter 5.
Stacks and Queues.
Queues Queues Queues.
Cinda Heeren / Geoffrey Tien
Stack and Queue APURBO DATTA.
CMSC 341 Lecture 5 Stacks, Queues
Lists, Stacks and Queues
Stacks and Queues 1.
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Stacks, Queues, and Deques
Stacks and Queues. 2 struct Node{ double data; Node* next; }; class List { public: List(); // constructor List(const List& list); // copy constructor.
Presentation transcript:

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

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.

 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 A top empty stack top push an elementpush another A B pop A

 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

 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

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

 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

 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.

 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; }

 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--]; } }

 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]; }

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

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

 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

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

Java Code Stack st = new Stack(); st.push(6); st.push(1); top 61

Java Code Stack st = new Stack(); st.push(6); st.push(1); st.push(7); top 617

Stack st = new Stack(); st.push(6); st.push(1); st.push(7); st.push(8); top 6178

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

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

 Push() and pop() either at the beginning or at the end of ADT List ◦ at the beginning: public void push(Object newItem) { list.insertAtHead(item); } // end push public Object pop() { return list.removeFromHead(); } // end pop

Chapter 5: Stacks24

 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: Stacks25

Chapter 5: Stacks26

 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: Stacks27

Chapter 5: Stacks28

Chapter 5: Stacks29

 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: Stacks30

 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: Stacks31

Chapter 5: Stacks32

 We can implement a stack using a linked list of nodes Chapter 5: Stacks33

 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: Stacks34

 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: Stacks35

Chapter 5: Stacks36

 Advantage of postfix form is that there is no need to group subexpressions in parentheses  No need to consider operator precedence 37

38

39

Chapter 5: Stacks40

Chapter 5: Stacks41

Chapter 5: Stacks42

43

44

45

46

 Queue ADT  Basic operations of queue ◦ Enqueuing, dequeuing.  Implementation of queue ◦ Array ◦ Linked list

 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.

 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

 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 Insert (Enqueue) Remove (Dequeue) rearfront

 Just as stacks can be implemented as arrays or linked lists, so with queues.  Dynamic queues have the same advantages over static queues as dynamic stacks have over static stacks

 There are several different algorithms to implement Enqueue and Dequeue  Naïve way ◦ When enqueuing, the front index is always fixed and the rear index moves forward in the array. front rear Enqueue(3) 3 front rear Enqueue(6) 3 6 front rear Enqueue(9) 3 6 9

 Naïve way ◦ When enqueuing, the front index is always fixed and the rear index moves forward in the array. ◦ When dequeuing, the element at the front the queue is removed. Move all the elements after it by one position. (Inefficient!!!) Dequeue() front rear 6 9 Dequeue() front rear 9 rear = -1 front

 Better way ◦ When an item is enqueued, make the rear index move forward. ◦ When an item is dequeued, the front index moves by one element towards the back of the queue (thus removing the front item, so no copying to neighboring elements is needed). XXXXOOOOO (rear) OXXXXOOOO (after 1 dequeue, and 1 enqueue) OOXXXXXOO (after another dequeue, and 2 enqueues) OOOOXXXXX (after 2 more dequeues, and 2 enqueues) (front) The problem here is that the rear index cannot move beyond the last element in the array.

 Using a circular array  When an element moves past the end of a circular array, it wraps around to the beginning, e.g. ◦ OOOOO7963  4OOOO7963 (after Enqueue(4)) ◦ After Enqueue(4), the rear index moves from 3 to 4.

 Empty queue ◦ back = front - 1  Full queue? ◦ the same! ◦ Reason: n values to represent n+1 states  Solutions ◦ Use a boolean variable to say explicitly whether the queue is empty or not ◦ Make the array of size n+1 and only allow n elements to be stored ◦ Use a counter of the number of elements in the queue

class Queue { public: Queue(int size = 10);// constructor bool IsEmpty(void); bool IsFull(void); bool Enqueue(double x); bool Dequeue(double & x); void DisplayQueue(void); private: int front;// front index int rear;// rear index int counter;// number of elements int maxSize;// size of array queue double[] values;// element array };

 Attributes of Queue ◦ front/rear : front/rear index ◦ counter : number of elements in the queue ◦ maxSize : capacity of the queue ◦ values : point to an array which stores elements of the queue  Operations of Queue ◦ IsEmpty : return true if queue is empty, return false otherwise ◦ IsFull : return true if queue is full, return false otherwise ◦ Enqueue : add an element to the rear of queue ◦ Dequeue : delete the element at the front of queue ◦ DisplayQueue : print all the data

 Queue(int size = 10) ◦ Allocate a queue array of size. By default, size = 10. ◦ front is set to 0, pointing to the first element of the array ◦ rear is set to -1. The queue is empty initially. Queue(int size ) { values=new double[size]; maxSize=size; front=0; rear=-1; counter =0; }

 Since we keep track of the number of elements that are actually in the queue: counter, it is easy to check if the queue is empty or full. Boolean IsEmpty() { if (counter != 0)return false; elsereturn true; } Boolean IsFull() { if (counter < maxSize)return false; elsereturn true; }

boolean Enqueue(double x) { if (IsFull()) { System.out.println("Error: the queue is full.“); return false; } else { // calculate the new rear position (circular) rear= (rear + 1) % maxSize; // insert new item values[rear]= x; // update counter counter++; return true; }

double Dequeue() throws EmptyQueueException { if (IsEmpty()) { System.out.println("Error: the queue is empty.“); throw EmptyQueueException; } else { // retrieve the front item x= values[front]; // move front front= (front + 1) % maxSize; // update counter counter--; return x;; }

void DisplayQueue() { System.out.print("front -->“); for (int i = 0; i < counter; i++) { if (i == 0) System.out.print( "\t”); else System.out.print("\t\t“); System.out.print(values[(front + i) % maxSize]); if (i != counter - 1) System.out.println(); else System.out.println( "\t<-- rear“); }

Create a queue with 5 items Enqueue 0,1,2,3,and 4 DisplayQueue(); Dequeue DisplayQueue(); Enqueue 7; DisplayQueue();

class Queue { // Data members Node front;// pointer to front node Node rear;// pointer to last node int counter;// number of elements // Constructor Queue() {// constructor front = rear = null; counter= 0; } boolean IsEmpty() { if (counter != 0) return false; else return true; } void Enqueue(double x); double Dequeue(); void DisplayQueue(); };

void Enqueue(double x) { Node newNode=new Node(x); if (IsEmpty()) { front=newNode; rear=newNode; } else { rear.setNextNode(newNode); rear=newNode; } counter++; } 8 rear newNode 5 58

double Dequeue() throws EmptyQueueException { if (IsEmpty()) { System.out.println("Error: the queue is empty.“); throw EmptyQueueException; } else { x=front.getData; Node nextNode=front.getNextNode(); front=nextNode; counter--; } 8 front 5 583

void DisplayQueue() { System.out.println("front -->“); Node currNode=front; for (int i = 0; i < counter; i++) { if (i == 0) System.out.print("\t“); else System.out.print("\t\t“); System.out.print(currNode.getData); if (i != counter - 1) System.out.println(); else System.out.println("\t<-- rear“); currNode=currNode.getNextNode(); }

 Queue implemented using linked list will be never full based on arraybased on linked list

Chapter 6: Queues

 Can be implemented as an adapter of any class that implements the List interface ◦ ArrayList ◦ Vector ◦ LinkedList  Removal is O(n) with a linked list ◦ O(n) when using ArrayList or Vector

Chapter 6: Queues  Time efficiency of using a single- or double- linked list to implement a queue is acceptable ◦ However there are some space inefficiencies  Storage space is increased when using a linked list due to references stored at each list node  Array Implementation ◦ Insertion at rear of array is constant time ◦ Removal from the front is linear time ◦ Removal from rear of array is constant time ◦ Insertion at the front is linear time

Chapter 6: Queues  All three implementations are comparable in terms of computation time  Linked-list implementations require more storage because of the extra space required for the links ◦ Each node for a single-linked list would store a total of two references ◦ Each node for a double-linked list would store a total of three references  A circular array that is filled to capacity would require half the storage of a single-linked list to store the same number of elements

Chapter 6: Queues  Simulation is used to study the performance of a physical system by using a physical, mathematical, or computer model of the system  Simulation allows designers of a new system to estimate the expected performance before building it  Simulation can lead to changes in the design that will improve the expected performance of the new system  Useful when the real system would be too expensive to build or too dangerous to experiment with after its construction

Chapter 6: Queues  System designers often use computer models to simulate physical systems ◦ Airline check-in counter for example ◦ A special branch of mathematics called queuing theory has been developed to study such problems

Chapter 6: Queues