Stacks, Queues & Deques CSC212.

Slides:



Advertisements
Similar presentations
Data Structures Through C
Advertisements

Stacks, Queues, and Linked Lists
Data Structures ADT List
1 Array-based Implementation An array Q of maximum size N Need to keep track the front and rear of the queue: f: index of the front object r: index immediately.
Stack & Queues COP 3502.
§3 The Stack ADT 1. ADT A stack is a Last-In-First-Out (LIFO) list, that is, an ordered list in which insertions and deletions are.
More on Stacks and Queues. As we mentioned before, two common introductory Abstract Data Type (ADT) that worth studying are Stack and Queue Many problems.
E.G.M. Petrakislists, stacks, queues1 Stacks Stack: restricted variant of list –Elements may by inserted or deleted from only one end  LIFO lists –Top:
CS 206 Introduction to Computer Science II 03 / 04 / 2009 Instructor: Michael Eckmann.
ADT Stacks and Queues. Stack: Logical Level “An ordered group of homogeneous items or elements in which items are added and removed from only one end.”
Queues 4/14/2017 5:24 PM 5.2 Queues Queues Dr Zeinab Eid.
 Balancing Symbols 3. Applications
CS Data Structures II Review COSC 2006 April 14, 2017
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
E.G.M. Petrakisstacks, queues1 Stacks  Stack: restricted variant of list  elements may by inserted or deleted from only one end : LIFO lists  top: the.
Stacks and Queues COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
1 Lecture 24 Abstract Data Types (ADT) –I Overview  What is an Abstract Data type?  What is Stack ADT?  Stack ADT Specifications  Array Implementation.
CHAPTER 6 Stacks. 2 A stack is a linear collection whose elements are added and removed from one end The last element to be put on the stack is the first.
Lecture 11 Sept 26, 2011 Goals convert from infix to postfix.
Implementing and Using Stacks
Stacks CS-240 & CS-341 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed.
1 Stack Data : a collection of homogeneous elements arranged in a sequence. Only the first element may be accessed Main Operations: Push : insert an element.
ADT Stacks and Queues. Stack: Logical Level “An ordered group of homogeneous items or elements in which items are added and removed from only one end.”
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
1 Stacks – Chapter 3 A stack is a data structure in which all insertions and deletions of entries are made at one end, called the top of the stack. Alternatively,
Stack and Queue.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part R1. Elementary Data Structures.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
ELEMENTARY DATA STRUCTURES Stacks, Queues, and Linked Lists.
Lab 7 Queue ADT. OVERVIEW The queue is one example of a constrained linear data structure. The elements in a queue are ordered from least recently added.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
1 Stacks & Queues CSC Stacks & Queues Stack: Last In First Out (LIFO). –Used in procedure calls, to compute arithmetic expressions etc. Queue: First.
© 2011 Pearson Addison-Wesley. All rights reserved 8 B-1 Chapter 8 (continued) Queues.
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) structure.
Stacks & Queues CSC 172 SPRING 2002 LECTURE 4 Agenda  Stack  Definition  Implementation  Analysis  Queue  Definition  Implementation  Analysis.
Stacks This presentation shows – how to implement the stack – how it can be used in real applications.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
 In general, Queue is line of person waiting for their turn at some service counter like ticket window at cinema hall, at bus stand or at railway station.
© 2004 Goodrich, Tamassia Queues. © 2004 Goodrich, Tamassia Stacks2 The Queue ADT The Queue ADT stores arbitrary objects Insertions and deletions follow.
Double-Ended Queues Chapter 5.
Objectives In this lesson, you will learn to: Define stacks
Stacks and Queues.
CSC 172 DATA STRUCTURES.
Priority Queue.
Stacks Stack: restricted variant of list
CMSC 341 Lecture 5 Stacks, Queues
Queues, Deques and Priority Queues
Queues.
Data Structures ADT List
Data Structures ADT List
ADT list.
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks and Queues 1.
Mutable Data (define mylist (list 1 2 3)) (bind ((new (list 4)))
Queues CSC212.
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Data Structures ADT List
Copyright © Aiman Hanna All rights reserved
ADT Queue (Array Implementation)
Stacks CS-240 Dick Steflik.
Stacks and Queues CSE 373 Data Structures.
Presentation transcript:

Stacks, Queues & Deques CSC212

Stacks & Queues Stack: Last In First Out (LIFO). Used in procedure calls, to compute arithmetic expressions etc. Queue: First In First Out (FIFO). Used in operating systems, simulations etc. Priority Queues: Highest priority item is served first. Used in operating systems, printer servers etc.

Stack (Linked Implementation) TOP

ADT Stack: Specification Elements: The elements are of a variable type <Type>. In a linked implementation an element is placed in a node. public class Node<T> extends Object { public T data; public Node<T> next; public Node () { data = null; next = null; } public Node (T val) { data = val; next = null; } }

ADT Stack: Specification Structure: the elements are linearly arranged, and ordered according to the order of arrival, most recently arrived element called top. Domain: the number of elements in the stack is bounded therefore the domain is finite. Type of elements: Stack

ADT Stack: Specification Operations: All operations operate on a stack S. Method Push (Type e) requires: Stack S is not full. input: Type e. results: Element e is added to the stack as its most recently added elements. output: none. Method Pop (Type e) requires: Stack S is not empty. input: results: the most recently arrived element in S is removed and its value assigned to e. output: Type e. Method Empty (boolean flag) input: results: If Stack S is empty then flag is true, otherwise false. output: flag.

ADT Stack: Specification Operations: Method Full (boolean flag). requires: input: . results: If S is full then Full is true, otherwise Full is false. output: flag.

ADT Stack (Linked Implementation) TOP Data Element Pointer A Linked Implementation of the Stack.

ADT Stack (Linked Implementation) public class LinkStack<T> { private Node<T> top; /* Creates a new instance of LinkStack */ public LinkStack() { top = null; } public boolean empty(){ return top == null; }

ADT Stack (Linked Implementation) public boolean full(){ return false; } public void push(T e){ Node<T> tmp = new Node(e); tmp.next = top; top = tmp;

ADT Stack (Linked Implementation) public T pop(){ T e = top.data; top = top.next; return e; }

Stack: Array Implementation public class ArrayStack<T> { private int maxsize; private int top; private T[] nodes; /** Creates a new instance of ArrayStack */ public ArrayStack(int n) { maxsize = n; top = -1; nodes = (T[]) new Object[n]; }

Stack: Array Implementation public boolean empty(){ return top == -1; } public boolean full(){ return top == maxsize-1;

Stack: Array Implementation public void push(T e){ nodes[++top] = e; } public T pop(){ return nodes[top--];

Applications of Stacks Some applications of stacks are: Balancing symbols. Computing or evaluating postfix expressions. Converting expressions from infix to postfix.

1. Balancing Symbols Expressions: mathematical (a + ((b-c)*d)) or programs have delimiters. begin { S1 S1 S2 { begin S2 S3 S3 begin } …. S4 end } end

1. Balancing Symbols Delimiters must be balanced. [()] is legal but [(]) illegal. A stack can be used to check if the delimiters are balanced. Read characters from the start of the expression to the end. If the token is a starting delimiter, push on to the stack, if closing delimiter pop the corresponding start delimiter from the stack.

1. Balancing Symbols If the stack is empty or if the popped symbol does not correspond to the closing symbol: report error. If stack is not empty at the end of file report an error.

2. Postfix Expressions Evaluating Postfix Expressions: Infix expression: 4.99*1.06+5.99+6.99*1.06 Value 18.69 correct parenthesis used. Value 19.37 incorrect  no parenthesis used. In postfix form, above expression becomes: 4.99 1.06 * 5.99 + 6.99 1.06*+ Advantage: no brackets are needed and a stack can be used to compute the expression.

2. Postfix Expressions Example: infix: 6*(5+((2+3)*8)+3) postfix: 6 5 2 3 + 8 * + 3 + *. Algorithm to compute postfix expression: Read the postfix expression left to right. When a number is read push it on the stack; when a operator is read, pop two numbers from the stack and carry out the operation on them, push the result back on the stack.

3. Infix to Postfix Conversion A stack can also be used to convert an infix expression to postfix expression. (See handout) Example: infix expression a + b * c + (d * e + f) * g to postfix expression a b c * + d e * f + g * + See class notes for more examples.

Queues Front Tail

ADT Queue: Specification Elements: The elements are of a variable type <Type>. In a linked implementation elements are placed in nodes. public class Node<T> extends Object { public T data; public Node<T> next; public Node () { data = null; next = null; } public Node (T val) { data = val; next = null; } }

ADT Queue: Specification Structure: the elements are linearly arranged, and ordered according to the order of arrival, most recently arrived element is called the tail and least recently arrived element the front or head. Domain: the number of elements in the queue is bounded therefore the domain is finite. Type of elements: Queue

ADT Queue: Specification Operations: Method Enqueue (Type e) requires: Queue Q is not full. input: Type e. results: Element e is added to the queue at its tail. output: none. Method Serve (Type e) requires: Queue Q is not empty. input: results: the element at the head of Q is removed and its value assigned to e. output: Type e. Method Length (int length) input: results: The number of element in the Queue Q is returned. output: length.

ADT Queue: Specification Operations: Method Full (boolean flag). requires: input: results: If Q is full then flag is set to true, otherwise flag is set to false. output: flag.

ADT Queue (Linked Implementation) public class LinkQueue <Type> { private Node<Type> head, tail; private int size; /** Creates a new instance of LinkQueue */ public LinkQueue() { head = tail = null; size = 0; }

ADT Queue (Linked Implementation) public boolean full() { return false; } public int length (){ return size;

ADT Queue (Linked Implementation) public void enqueue (Type e) { if (tail == null){ head = tail = new Node(e); } else { tail.next = new Node(e); tail = tail.next; size++;

ADT Queue (Linked Implementation) public Type serve() { Node<Type> tmp; Type x; tmp = head; x = head.data; head = head.next; size--; if (size == 0) tail = null; return x; }

ADT Queue (Array Implementation) Array implementation of the queue…a fixed size array is used to store the data elements. As data elements are enqueued & served the queue crawls through the array from low to high index values. As the queue crawls forward, it also expands and contracts.

ADT Queue (Array Implementation) Head Tail After one En-queue and one Serve Head Tail

ADT Queue (Array Implementation) Head Tail Where to En-queue this?

ADT Queue (Array Implementation) MaxSize-1 Tail Head Wrap Round

ADT Queue (Array Implementation) Tail Head MaxSize - 1

ADT Queue (Array Implementaion) public class ArrayQueue <T> { private int maxsize; private int size; private int head, tail; private T[] nodes; /** Creates a new instance of ArrayQueue */ public ArrayQueue(int n) { maxsize = n; size = 0; head = tail = 0; nodes = (T[]) new Object[n]; }

ADT Queue (Array Implementation) public boolean full () { return size == maxsize ? true : false; } public int length () { return size; public void enqueue(T e) { nodes[tail] = e; tail = (tail + 1) % maxsize; size++;

ADT Queue (Array Implementation) public T serve () { T e = nodes[head]; head = (head + 1) % maxsize; size--; return e; }

Priority Queue Each data element has a priority associated with it.Highest priority item is served first. Real World Priority Queues: hospital emergency rooms…most sick patients treated first, events in a computer system, etc. Priority Queue can be viewed as: View 1: Priority queue as an ordered list. View 2: Priority queue as a set.

ADT Priority Queue Specification: Elements: The elements are of type PQNode. Each node has in it a data element of variable type <Type> and priority of type Priority ( which could be int type). public class PQNode<T> { private T data; private Priority priority; public PQNode<T> next; public PQNode() { next = null; } public PQNode(T e, Priority p) { data = e; priority = p; }

ADT Priority Queue Structure: the elements are linearly arranged, and may be ordered according to a priority value, highest priority element is called the tail and least priority element the front or head. Domain: the number of nodes in the queue is bounded therefore the domain is finite. Type of elements: PriorityQueue

ADT Priority Queue Operations: Method Enqueue (Type e, Priority p) requires: PQ is not full. input: e, p. results: Element e is added to the queue according to its priority. output: none. Method Serve (Type e, Priority p) requires: PQ is not empty. input: results: the element at the head of PQ is removed and returned. output: e, p. Method Length (int length) input: results: The number of element in the PQ is returned. output: length.

ADT Priority Queue Operations: Method Full (boolean flag). requires: input: results: If PQ is full then flag is set to true, otherwise flag is set to false. output: flag.

ADT Priority Queue Array Implementation el 10 8 7 5 Head Tail el el el Linked Implementation Insert Where? el 10 8 7 5 Head Tail

ADT Priority Queue (Linked) public class LinkPQ<T> { private int size; private PQNode<T> head, tail; /* tail is of no use here. */ public LinkPQ() { head = tail = null; size = 0; } public int length (){ return size; }

ADT Priority Queue (Linked) public int length (){ return size; } public boolean full () { return false;

ADT Priority Queue (Linked) public void enqueue(T e, int pty) { PQNode<T> p, q, tmp; if ((size == 0) || (pty > head.Priority())) { tmp = new PQNode<T>(e, pty); tmp.next = head; head = tmp; } else { p = head; q = null; while ((p != null) && (p.Priority() > pty)) { q = p; p = p.next; } tmp.next = p; q.next = tmp; } }

ADT Priority Queue (Linked) public T serve (Priority pty){ T e = head.get_data(); pty.set_value(head.get_priority().get_value()); head = head.next; size--; return(e); }

ADT Priority Queue Implementations Array Implementation: Enqueue is O(n), Serve is O(1). Linked List: Enqueue is O(n), Serve is O(1). Heap: Enqueue is O(log n), Serve is O(log n)  Heaps to be discussed later.

Double-Ended Queues Double ended queue (or a deque) supports insertion and deletion at both the front and the tail of the queue. Supports operations: addFirst( ), addLast(), removeFirst( ) and removeLast( ). Can be used in place of a queue or a stack.

Double-Ended Queues Operations: (Assume all operations are performed on deque DQ) Method addFirst (Type e) requires: DQ is not full. input: e. results: Element e is added to DQ as first element. output: none. Method addLast (Type e) requires: DQ is not full. input: e results: Element e is added to DQ as last element. output: none. Method removeFirst (Type e) requires: DQ is not empty. input: none results: Removes and returns the first element of DQ. output: e.

Double-Ended Queues Method removeLast (Type e) requires: DQ is not empty. input: none. results: Removes and returns the last element of DQ. output: e. Method getFirst (Type e) requires: DQ is not empty. input: none results: Returns the first element of DQ. output: e. Method getLast (Type e) results: Returns the last element of DQ. output: e Method size (int x) input: none results: Returns the number of elements in DQ. output: x

Double-Ended Queues Method isEmpty (boolean x) input: none results: if DQ is empty returns x as true otherwise false. output: x