Stacks, Queues, and Deques

Similar documents
This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

What is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation

DATA STRUCTURE - QUEUE

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

Universidad Carlos III de Madrid

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Data Structures Using C++ 2E. Chapter 5 Linked Lists

STACKS,QUEUES, AND LINKED LISTS

DATA STRUCTURE - STACK

Chapter 3: Restricted Structures Page 1

Module 2 Stacks and Queues: Abstract Data Types

Common Data Structures

Queues and Stacks. Atul Prakash Downey: Chapter 15 and 16

DATA STRUCTURES USING C

10CS35: Data Structures Using C

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Programming with Data Structures

Linked Lists Linked Lists, Queues, and Stacks

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

Data Structures and Algorithms Stacks and Queues

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

Sequential Data Structures

CmpSci 187: Programming with Data Structures Spring 2015

7.1 Our Current Model

Introduction to Data Structures

PES Institute of Technology-BSC QUESTION BANK

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Analysis of a Search Algorithm

Data Structures and Algorithms

Data Structures in the Java API

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

Algorithms and Data Structures

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Glossary of Object Oriented Terms

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

ADTs,, Arrays, Linked Lists

Stacks. Linear data structures

Basic Data Structures and Algorithms

Linked Lists: Implementation Sequences in the C++ STL

Data Structures and Algorithms

Node-Based Structures Linked Lists: Implementation

PROGRAMMING CONCEPTS AND EMBEDDED PROGRAMMING IN C, C++ and JAVA: Lesson-4: Data Structures: Stacks

Data Structures UNIT III. Model Question Answer

Sequences in the C++ STL

List, Stack and Queue. Tom Chao Zhou CSC2100B Data Structures Tutorial 3

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Application of Stacks: Postfix Expressions Calculator (cont d.)

Abstract Data Types. Chapter 2

Stack & Queue. Darshan Institute of Engineering & Technology. Explain Array in detail. Row major matrix No of Columns = m = u2 b2 + 1

Java Interview Questions and Answers

St S a t ck a ck nd Qu Q eue 1

Cpt S 223. School of EECS, WSU

Unordered Linked Lists

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

Practical Session 4 Java Collections

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

Introduction to Data Structures and Algorithms

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

1 Description of The Simpletron

14 Stacks, Queues, And Linked Lists

Linear ADTs. Restricted Lists. Stacks, Queues. ES 103: Data Structures and Algorithms 2012 Instructor Dr Atul Gupta

Lecture Notes on Stacks & Queues

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Data Structures and Data Manipulation

LINKED DATA STRUCTURES

Atmiya Infotech Pvt. Ltd. Data Structure. By Ajay Raiyani. Yogidham, Kalawad Road, Rajkot. Ph : ,

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

Stacks. Data Structures and Data Types. Collections

Java Software Structures

Introduction to Stacks

Inside the Java Virtual Machine

Chapter 8: Bags and Sets

recursion, O(n), linked lists 6/14

D06 PROGRAMMING with JAVA

Evolving Data Structures with Genetic Programming

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Monitors, Java, Threads and Processes

Data Structures Using C++

Queues. Manolis Koubarakis. Data Structures and Programming Techniques

CS11 Java. Fall Lecture 7

Data Structures. Level 6 C Module Descriptor

- Easy to insert & delete in O(1) time - Don t need to estimate total memory needed. - Hard to search in less than O(n) time

3 Abstract Data Types and Search

Circular Linked List. Algorithms and Data Structures

Data Structures and Algorithms Lists

Algorithms and Abstract Data Types

Transcription:

Stacks, Queues, and Deques

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 were inserted A queue is a first in, first out (FIFO) data structure Items are removed from a queue in the same order as they were inserted A deque is a double-ended queue items can be inserted and removed at either end 2

Array implementation of stacks To implement a stack, items are inserted and removed at the same end (called the top) Efficient array implementation requires that the top of the stack be towards the center of the array, not fixed at one end To use an array to implement a stack, you need both the array itself and an integer The integer tells you either: Which location is currently the top of the stack, or How many elements are in the stack 3

Pushing and popping stk: 0 1 2 3 4 5 6 7 8 9 17 23 97 44 top = 3 or count = 4 If the bottom of the stack is at location 0, then an empty stack is represented by top = -1 or count = 0 To add (push) an element, either: Increment top and store the element in stk[top], or Store the element in stk[count] and increment count To remove (pop) an element, either: Get the element from stk[top] and decrement top, or Decrement count and get the element in stk[count] 4

After popping stk: 0 1 2 3 4 5 6 7 8 9 17 23 97 44 top = 2 or count = 3 When you pop an element, do you just leave the deleted element sitting in the array? The surprising answer is, it depends If this is an array of primitives, or if you are programming in C or C++, then doing anything more is just a waste of time If you are programming in Java, and the array contains objects, you should set the deleted array element to null Why? To allow it to be garbage collected! 5

Sharing space Of course, the bottom of the stack could be at the other end stk: 0 1 2 3 4 5 6 7 8 9 44 97 23 17 top = 6 or count = 4 Sometimes this is done to allow two stacks to share the same storage area stks: 0 1 2 3 4 5 6 7 8 9 49 57 3 44 97 23 17 topstk1 = 2 topstk2 = 6 6

Error checking There are two stack errors that can occur: Underflow: trying to pop (or peek at) an empty stack Overflow: trying to push onto an already full stack For underflow, you should throw an exception If you don t catch it yourself, Java will throw an ArrayIndexOutOfBounds exception You could create your own, more informative exception For overflow, you could do the same things Or, you could check for the problem, and copy everything into a new, larger array 7

Pointers and references In C and C++ we have pointers, while in Java we have references These are essentially the same thing The difference is that C and C++ allow you to modify pointers in arbitrary ways, and to point to anything In Java, a reference is more of a black box, or ADT Available operations are: dereference ( follow ) copy compare for equality There are constraints on what kind of thing is referenced: for example, a reference to an array of int can only refer to an array of int 8

Creating references The keyword new creates a new object, but also returns a reference to that object For example, Person p = new Person("John") new Person("John") creates the object and returns a reference to it We can assign this reference to p, or use it in other ways 9

mystack: Creating links in Java 44 97 23 17 class Cell { int value; Cell next; Cell (int v, Cell n) { value = v; next = n; } } Cell temp = new Cell(17, null); temp = new Cell(23, temp); temp = new Cell(97, temp); Cell mystack = new Cell(44, temp); 10

Linked-list implementation of stacks Since all the action happens at the top of a stack, a singlylinked list (SLL) is a fine way to implement it The header of the list points to the top of the stack mystack: 44 97 23 17 Pushing is inserting an element at the front of the list Popping is removing an element from the front of the list 11

Linked-list implementation details With a linked-list representation, overflow will not happen (unless you exhaust memory, which is another kind of problem) Underflow can happen, and should be handled the same way as for an array implementation When a node is popped from a list, and the node references an object, the reference (the pointer in the node) does not need to be set to null Unlike an array implementation, it really is removed-- you can no longer get to it from the linked list Hence, garbage collection can occur as appropriate 12

Array implementation of queues A queue is a first in, first out (FIFO) data structure This is accomplished by inserting at one end (the rear) and deleting from the other (the front) myqueue: front = 0 0 1 2 3 4 5 6 7 17 23 97 44 rear = 3 To insert: put new element in location 4, and set rear to 4 To delete: take element from location 0, and set front to 1 13

Array implementation of queues front = 0 rear = 3 Initial queue: After insertion: After deletion: 17 23 97 44 17 23 97 44 333 23 97 44 333 front = 1 rear = 4 Notice how the array contents crawl to the right as elements are inserted and deleted This will be a problem after a while! 14

Circular arrays We can treat the array holding the queue elements as circular (joined at the ends) myqueue: 0 1 2 3 4 5 6 7 44 55 11 22 33 rear = 1 front = 5 Elements were added to this queue in the order 11, 22, 33, 44, 55, and will be removed in the same order Use: front = (front + 1) % myqueue.length; and: rear = (rear + 1) % myqueue.length; 15

Full and empty queues If the queue were to become completely full, it would look like this: myqueue: 0 1 2 3 4 5 6 7 44 55 66 77 88 11 22 33 rear = 4 front = 5 If we were then to remove all eight elements, making the queue completely empty, it would look like this: myqueue: 0 1 2 3 4 5 6 7 This is a problem! rear = 4 front = 5 16

Full and empty queues: solutions Solution #1: Keep an additional variable myqueue: 0 1 2 3 4 5 6 7 44 55 66 77 88 11 22 33 count = 8 rear = 4 front = 5 Solution #2: (Slightly more efficient) Keep a gap between elements: consider the queue full when it has n-1 elements myqueue: 0 1 2 3 4 5 6 7 44 55 66 77 11 22 33 rear = 3 front = 5 17

Linked-list implementation of queues In a queue, insertions occur at one end, deletions at the other end Operations at the front of a singly-linked list (SLL) are O(1), but at the other end they are O(n) Because you have to find the last element each time BUT: there is a simple way to use a singly-linked list to implement both insertions and deletions in O(1) time You always need a pointer to the first thing in the list You can keep an additional pointer to the last thing in the list 18

SLL implementation of queues In an SLL you can easily find the successor of a node, but not its predecessor Remember, pointers (references) are one-way If you know where the last node in a list is, it s hard to remove that node, but it s easy to add a node after it Hence, Use the first element in an SLL as the front of the queue Use the last element in an SLL as the rear of the queue Keep pointers to both the front and the rear of the SLL 19

Enqueueing a node last first Node to be enqueued 44 97 23 17 To enqueue (add) a node: Find the current last node Change it to point to the new last node Change the last pointer in the list header 20

Dequeueing a node last first 44 97 23 17 To dequeue (remove) a node: Copy the pointer from the first node into the header 21

Queue implementation details With an array implementation: you can have both overflow and underflow you should set deleted elements to null With a linked-list implementation: you can have underflow overflow is a global out-of-memory condition there is no reason to set deleted elements to null 22

Deques A deque is a double-ended queue Insertions and deletions can occur at either end Implementation is similar to that for queues Deques are not heavily used You should know what a deque is, but we won t explore them much further 23

Stack ADT The Stack ADT, as provided in java.util.stack: Stack(): the constructor boolean empty() Object push(object item) Object peek() Object pop() int search(object o): Returns the 1-based position of the object on this stack 24

A queue ADT Java does not provide a queue class Here is a possible queue ADT: Queue(): the constructor boolean empty() Object enqueue(object item): add at element at the rear Object dequeue(): remove an element from the front Object peek(): look at the front element int search(object o): Returns the 1-based position from the front of the queue 25

A deque ADT Java does not provide a deque class Here is a possible deque ADT: Deque(): the constructor boolean empty() Object addatfront(object item) Object addatrear(object item) Object getfromfront() Object getfromrear() Object peekatfront() Object peekatrear() int search(object o): Returns the 1-based position from the front of the deque 26

Using Vectors You could implement a deque with java.util.vector: addatfront(object) insertelementat(object, 0) addatrear(object item) add(object) getfromfront() remove(0) getfromrear() remove(size() 1) Would this be a good implementation? Why or why not? 27

The End 28