291205 Data Structures and Algorithm Analysis Dr. Ken Cosh Stacks ‘n’ Queues.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Chapter 6 Queues and Deques.
Chapter 4: Stacks and Queues
Stack & Queues COP 3502.
Queues A waiting line that grows by adding elements to its end and shrinks by taking elements from its front Line at the grocery store Cars in traffic.
Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
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.
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.
ADT Queue 1. What is a Queue? 2. STL Queue 3. Array Implementation of Queue 4. Linked List Implementation of Queue 5. Priority Queue.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 18 Stacks.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 18: Stacks And Queues.
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
1 CSC 211 Data Structures Lecture 22 Dr. Iftikhar Azim Niaz 1.
 Abstract Data Type Abstract Data Type  What is the difference? What is the difference?  Stacks Stacks  Stack operations Stack operations  Parsing.
Queue RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
ALGORITHMS FOR ISNE DR. KENNETH COSH WEEK 3.
Main Index Contents 11 Main Index Contents Model for a Queue Model for a Queue The Queue The Queue ADTQueue ADT (3 slides) Queue ADT Radix Sort Radix Sort.
1 Queues CPS212 Gordon College. 2 Introduction to Queues A queue is a waiting line – seen in daily life –Real world examples – toll booths, bank, food.
Stacks, Queues & Deques CSC212.
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.
Stacks, Queues, and Deques. 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.
Stacks, Queues, and Deques
Chapter 16 Stacks and Queues Saurav Karmakar Spring 2007.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 8 Stacks and Queues Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Stacks and queues Basic operations Implementation of stacks and queues Stack and Queue in java.util Data Structures and Algorithms in Java, Third EditionCh04.
Adapted from instructor resources Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
Chapter 16 Stacks & Queues. Objective In this chapter we will learn:  Stacks  Queues  Different implementations (arrays and linked list) of both 
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 18 Stacks and Queues.
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,
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Stacks And Queues Chapter 18.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 18: Stacks and Queues.
CMSC 341 Deques, Stacks and Queues. 2/20/20062 The Double-Ended Queue ADT A Deque (rhymes with “check”) is a “Double Ended QUEue”. A Deque is a restricted.
Queues Chapter 5 Queue Definition A queue is an ordered collection of data items such that: –Items can be removed only at one end (the front of the queue)
Exam Review 2 Chapter 5 – 9 CSC212 FG CS Dept, CCNY.
Give Eg:? Queues. Introduction DEFINITION: A Queue is an ordered collection of element in which insertions are made at one end and deletions are made.
1 Queues Chapter 4. 2 Objectives You will be able to Describe a queue as an ADT. Build a dynamic array based implementation of a queue ADT.
Queues Another Linear ADT Copyright © 2009 Curt Hill.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
Lecture 10 b Stacks b Queues. 2 Stacks b A stack ADT is linear b Items are added and removed from only one end of a stack b It is therefore LIFO: Last-In,
Data Structures and Algorithm Analysis Dr. Ken Cosh Linked Lists.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 18: Stacks and Queues.
1 Data Structures and Algorithms Queue. 2 The Queue ADT Introduction to the Queue data structure Designing a Queue class using dynamic arrays Linked Queues.
Cpt S 122 – Data Structures Abstract Data Types
18 Chapter Stacks and Queues
CS505 Data Structures and Algorithms
Chapter 18: Stacks and Queues.
Unit 4 Stacks And Queues King Fahd University of Petroleum & Minerals
CC 215 Data Structures Queue ADT
Queues Rem Collier Room A1.02
Stack and Queue APURBO DATTA.
CMSC 341 Lecture 5 Stacks, Queues
Stacks, Queues, and Deques
Chapter 19: Stacks and Queues.
Queues.
Deques, Stacks and Queues
Stacks, Queues, and Deques
Stack A data structure in which elements are inserted and removed only at one end (called the top). Enforces Last-In-First-Out (LIFO) Uses of Stacks Evaluating.
Pointers & Dynamic Data Structures
CMSC 341 Stacks and Queues 4/17/2019.
Stacks, Queues, and Deques
CSCS-200 Data Structure and Algorithms
Getting queues right … finally (?)
Chapter 4 Stacks and Queues
Presentation transcript:

Data Structures and Algorithm Analysis Dr. Ken Cosh Stacks ‘n’ Queues

Last Week Linked Lists –Singly, Doubly, Circular. –Skip Lists –Self Organising Lists –Double Ended Queues (or Deque)

Also this week, 2 More Data Types; –Stacks –Queues

Stacks Stacks are linear data structures, that can only be accessed at one end for storing and retrieving data. New data is added to the top of a stack, and data is also retrieved from the top of the stack. Similar to a stack of trays in a canteen. It is a LIFO structure (Last In First Out).

Queues Queues are also linear data structures, however it is a waiting line, where both ends are used. Data is added to one end of the line, and retrieved from the other. Similar to a Queue in a bank etc. It is a FIFO structure (First In First Out).

Stacks Key operations; –Clear() – clears the stack –isEmpty() – Tests if the stack is empty –Push(el) – adds ‘el’ to the top of the stack –Pop() – Retrieves the top element off the stack –topEl() – Returns the top element without removing it.

Stack Use Consider the problem of matching delimiters in a program; –Delimiters : [, ], {, }, (, ), /*, */ Problem; to test the delimiters have been correctly matched; –A) while(m<(n[8] + o)) {p=7; /*initialise p*/ r=6;} –B) a = b + ( c – d ) * ( e - f )) Case A should return a success, while case B should return an error.

Stack Case A) while(m<(n[8] + o)) {p=7; /*initialise p*/ r=6;} –Add to stack (-( –Add to stack (-( ( –Add to stack [-( ( [ –Remove from stack [-( ( –Remove from stack (-( –Remove from stack (- –Add to stack {-{ –Add to stack /*-{ /* –Remove from stack */-} –Remove from stack }-

Implementing a Stack Option 1) A Vector Option 2) A Linked List Which is better?

Implementing as a Vector #ifndef STACK #define STACK #include template class Stack{ public: Stack() { pool.reserve(capacity); } void clear() { pool.clear(); } bool isEmpty() const { return pool.empty(); } T& topEl() { return pool.back(); } T pop() { T el = pool.back(); pool.pop_back(); return el; } void push(const T& el) { pool.push_back(el); } private: vector pool; }; #endif //STACK

Implementing as a Linked List #ifndef LL_STACK #define LL_STACK #include template class LLStack { public: LLStack() { } void clear() { lst.clear(); } bool isEmpty() const { return lst.empty(); } T& topEl() {return lst.back(); } T pop() { T el = lst.back(); lst.pop_back(); return el; } void push(const T& el) { lst.push_back(el); } private: list lst; }; #endif // LL_STACK

Comparison The linked list matches the stack more closely – there are no redundant ‘capacity’. In the vector implementation the capacity can be larger than the size. Neither implementation forces the program to commit to the size of the stack, although it can be predicted in the vector implementation. Pushing and Popping for both implementations is in constant time; O(1). Pushing in the vector implementation when the capacity is full requires allocating new memory and copying the stack to the new vector; O(n).

Queue Key Operations; –Clear() – Clear the queue –isEmpty() – Check if the queue is empty –Enqueue(el) – Add ‘el’ to end of queue –Dequeue() – Take first element from queue –firstEl() – Return first element without removing it.

Queue Use Simulating any queue; –To determine how many staff are needed in a bank to maintain a good level of service, –Or, how many kiosks to open at the motorway toll.

Option 1 - Array The obvious problem with using an array is that as you remove elements from the front of the queue, space then becomes wasted at the front of the array. This can be avoided using a ‘circular array’, which reuses the first part of the array ? 5 6 7

Circular Array As elements at the front of the array are removed those cells become available when the array reaches the end. In reality a circular array is simply a one dimensional array, where the enqueue() and dequeue() functions have the extra overhead of; –Checking if they are adding / removing the element in the last cell of the array. –Checking they aren’t overwriting the first element. Therefore the circular array is purely a way of visualising the approach. The code on the next slides demonstrates some of the functions you might need if you chose to implement using an array.

Queue – Circular Array #ifndef ARRAY_QUEUE #define ARRAY_QUEUE template class ArrayQueue { public: ArrayQueue() { first = last = -1; } void enqueue(T); T dequeue(); bool isFull() { return first == 0 && last == size-1 || first == last -1; } bool isEmpty() { return first == -1 } private: int first, last; T storage[size]; };

Queue – Circular Array cont. template void ArrayQueue ::enqueue(T el) { if (!isFull()) if (last == size-1 || last == -1) { storage[0] = el; last = 0; if (first == -1) first = 0; } else storage[++last] = el; else cout << “Full queue.\n”; } template T ArrayQueue ::dequeue() { T tmp; tmp = storage[first]; if (first == last) last = first = -1; else if (first == size -1) first = 0; else first++; return tmp; } #endif //ARRAY_QUEUE

Option 2 – Doubly Linked List A perhaps better implementation uses a doubly linked list. –Both enqueuing and dequeuing can be performed in constant time O(1). –If a singly linked list was chosen then O(n) operations are needed to find the ‘other’ end of the list either for enqueuing or dequeuing.

Doubly Linked List #ifndef DLL_QUEUE #define DLL_QUEUE #include template class Queue { public: Queue() { } void clear() { lst.clear(); } bool isEmpty() const { return lst.empty(); } T& front() { return lst.front(); } T dequeue() { T el = lst.front(); lst.pop_front(); return el; } void enqueue(const T& el) { lst.push_back(el); } private: list lst; }; #endif // DLL_QUEUE

Priority Queues Queuing is rarely that simple! What happens when a police car approaches a toll point? Or a disabled person visits a bank? Or in fact many of the queuing situations in Thailand? A standard queue model won’t effectively model the queuing experience. In priority queues elements are dequeued according to their priority and their current queue position.

Queue Theory There has been much research into how to best solve the priority queuing problem – if you are interested simply look up “Queue Theory”.

Linked List Variation We can use a linked list to model the new queue, by simply making a simple variation. There are 2 options; –When adding a new element to the list, search through the list to place it in the appropriate position – O(n) for enqueue(). –When removing an element, search through the list to find the highest priority element – O(n) for dequeue().

Alternative Have a short ‘ordered’ list, and a longer unordered list. Priority elements are added to the ordered list, non-priority elements are in the longer list. From this model, dequeue() is of course constant O(1), but enqueue() can be O(√n) with maximised efficiency. (Blackstone 1981)

STL - Stack Stack exists in the STL, with the following key member functions; bool empty() const – returns true if stack is empty. void pop() – removes the top element void push(const T& el) – insets el to the top of the stack size_type size() const – returns the size of the stack stack() – constructor for empty stack T& top() – returns top element from stack

STL - Queue Queue exists in the STL, with the following key member functions; T& back() – returns last element bool empty() const – returns true if queue empty T& front() – returns first element in queue void pop() – remove first element in queue void push(const T& el) – insert el at back of queue queue() – constructor for empty queue size_type size() const – returns size of queue

Programming Assignment A Queue or Stack can be used to perform calculations on very large integers. There is a limit to the size of integers, so performing the following calculation can be difficult; – Write a program that can perform the 4 key arithmetic operations, +, -, * on very large integers, returning an integer.