STACKS,QUEUES, AND LINKED LISTS



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

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

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

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

Outline. The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack. Stacks 2

Universidad Carlos III de Madrid

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

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

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

Sequential Data Structures

Chapter 3: Restricted Structures Page 1

Analysis of a Search Algorithm

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

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

Unordered Linked Lists

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

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

Module 2 Stacks and Queues: Abstract Data Types

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

ADTs,, Arrays, Linked Lists

7.1 Our Current Model

Introduction to Stacks

Programming with Data Structures

Linked Lists Linked Lists, Queues, and Stacks

10CS35: Data Structures Using C

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

DATA STRUCTURE - QUEUE

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

CmpSci 187: Programming with Data Structures Spring 2015

Common Data Structures

DATA STRUCTURE - STACK

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

Algorithms and Data Structures

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

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

Data Structures and Algorithms

Data Structures and Algorithms Stacks and Queues

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

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

&DUORV'HOJDGR.ORRV,QJHQLHUtD7HOHPiWLFD 8QLY&DUORV,,,GH0DGULG. Copyright 2001 Java: Pilas y Colas / 1

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

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

Data Structures in the Java API

D06 PROGRAMMING with JAVA

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

14 Stacks, Queues, And Linked Lists

PES Institute of Technology-BSC QUESTION BANK

Linked List as an ADT (cont d.)

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

Data Structures and Algorithms Lists

DATA STRUCTURES USING C

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

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

LINKED DATA STRUCTURES

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

Data Structures UNIT III. Model Question Answer

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

Stacks. Data Structures and Data Types. Collections

Algorithms and Data Structures Written Exam Proposed SOLUTION

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

Abstract Data Types. Chapter 2

Basic Data Structures and Algorithms

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!

Introduction to Data Structures and Algorithms

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

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

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

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

Glossary of Object Oriented Terms

Stacks. Linear data structures

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

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Data Structures and Data Manipulation

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

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

CS 111 Classes I 1. Software Organization View to this point:

Java Software Structures

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

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

Data Types. Abstract Data Types. ADTs as Design Tool. Abstract Data Types. Integer ADT. Principle of Abstraction

Data Structures and Algorithms V Otávio Braga

Queue ADT. March 16, 2000

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

Data Structures and Algorithms Written Examination

Ordered Lists and Binary Trees

Cpt S 223. School of EECS, WSU

COMPUTER SCIENCE. Paper 1 (THEORY)

Algorithms and Abstract Data Types

Software Engineering Techniques

Algorithms and Data Structures

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

Singly linked lists (continued...)

EE2204 DATA STRUCTURES AND ALGORITHM (Common to EEE, EIE & ICE)

Collaboration policy. Where to get help (but no code in ) Office hours Lab TAs in Friend 008/009 Bounce ideas (but not code) off classmates

Chapter 8: Bags and Sets

PROBLEMS (Cap. 4 - Istruzioni macchina)

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

Algorithms and Data S tructures Structures Stack, Queues, and Applications Applications Ulf Leser

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Lecture 12 Doubly Linked Lists (with Recursion)

Transcription:

STACKS,QUEUES, AND LINKED LISTS Stacks Queues Linked Lists Double-Ended Queues Case Study: A Stock Analysis Applet 1

Stacks Astack is a container of objects that are inserted and removed according to the last-in-first-out (LIFO) principle. Objects can be inserted at any time, but only the last (the most-recently inserted) object can be removed. Inserting an item is known as pushing onto the stack. Popping off the stack is synonymous with removing an item. A PEZ dispenser as an analogy: 2

The Stack Abstract Data Type A stack is an abstract data type (ADT) that supports two main methods: - push(o): Inserts object o onto top of stack Input: Object; Output: none - pop(): Removes the top object of stack and returns it; if stack is empty an error occurs Input: none; Output: Object The following support methods should also be defined: - size(): Returns the number of objects in stack Input: none; Output: integer - isempty(): Return a boolean indicating if stack is empty. Input: none; Output: boolean - top(): return the top object of the stack, without removing it; if the stack is empty an error occurs. Input: none; Output: Object 3

A Stack Interface in Java While, the stack data structure is a built-in class of Java s java.util package, it is possible, and sometimes preferable to define your own specific one, like this: public interface Stack { // accessor methods public int size(); // return the number of // elements in the stack public boolean isempty(); // see if the stack // is empty public Object top() // return the top element throws StackEmptyException; // if called on // an empty stack // update methods } public void push (Object element); // push an // element onto the stack public Object pop() // return and remove the // top element of the stack throws StackEmptyException; // if called on // an empty stack 4

S An Array-Based Stack Create a stack using an array by specifying a maximum size N for our stack, e.g. N = 1,000. The stack consists of an N-element array S and an integer variable t, the index of the top element in array S. Array indices start at 0, so we initialize t to -1 Pseudo-code Algorithm size(): return t +1 Algorithm isempty(): return (t<0) Algorithm top(): if isempty() then throw a StackEmptyException return S[t]...... 0 1 2 t N 1 5

An Array-Based Stack (contd.) Pseudo-Code (contd.) Algorithm push(o): if size() = N then throw a StackFullException t t + 1 S[t] o Algorithm pop(): if isempty() then throw a StackEmptyException e S[t] S[t] null t t-1 return e Each of the above method runs in constant time (O(1)) The array implementation is simple and efficient. There is an upper bound, N, on the size of the stack. The arbitrary value N may be too small for a given application, or a waste of memory. 6

Array-Based Stack: a Java Implementation public class ArrayStack implements Stack { // Implementation of the Stack interface // using an array. public static final int CAPACITY = 1000; // default // capacity of the stack private int capacity; // maximum capacity of the // stack. private Object S[]; // S holds the elements of // the stack private int top = -1; // the top element of the // stack. public ArrayStack() { // Initialize the stack // with default capacity this(capacity); } public ArrayStack(int cap) { // Initialize the // stack with given capacity capacity = cap; S = new Object[capacity]; } 7

Array-Based Stack in Java (contd.) public int size() { //Return the current stack // size return (top + 1); } public boolean isempty() { // Return true iff // the stack is empty return (top < 0); } public void push(object obj) { // Push a new // object on the stack if (size() == capacity) throw new StackFullException( Stack overflow. ); S[++top] = obj; } public Object top() // Return the top stack // element throws StackEmptyException { if (isempty()) throw new StackEmptyException( Stack is empty. ); return S[top]; } 8

Array-Based Stack in Java (contd.) public Object pop() // Pop off the stack element } throws StackEmptyException { Object elem; if (isempty()) throw new StackEmptyException( Stack is Empty. ); elem = S[top]; S[top--] = null; // Dereference S[top] and // decrement top return elem; } 9

Casting With a Generic Stack Have an ArrayStack that can store only Integer objects or Student objects. In order to do so using a generic stack, the return objects must be cast to the correct data type. A Java code example: public static Integer[] reverse(integer[] a) { ArrayStack S = new ArrayStack(a.length); Integer[] b = new Integer[a.length]; for (int i = 0; i < a.length; i++) S.push(a[i]); for (int i = 0; i < a.length; i++) b[i] = (Integer)(S.pop()); return b; 10

Stacks in the Java Virtual Machine Each process running in a Java program has its own Java Method Stack. Each time a method is called, it is pushed onto the stack. The choice of a stack for this operation allows Java to do several useful things: - Perform recursive method calls - Print stack traces to locate an error Java also includes an operand stack which is used to evaluate arithmetic instructions, i.e. Integer add(a, b): OperandStack Op Op.push(a) Op.push(b) temp1 Op.pop() temp2 Op.pop() Op.push(temp1 + temp2) return Op.pop() 11

Java Method Stack main() { int i=5; fool: PC = 320 m = 7 14 } cool(i); cool: PC = 216 j = 5 k = 7 main: PC = 14 i = 5 Java Stack 216 320 cool(int j) { int k=7; fool(k); } fool(int m) { } Java Program 12

Queues A queue differs from a stack in that its insertion and removal routines follows the first-in-first-out (FIFO) principle. Elements may be inserted at any time, but only the element which has been in the queue the longest may be removed. Elements are inserted at the rear (enqueued) and removed from the front (dequeued) Front Rear Queue a 0 a 1 a 2... a n-1 13

The Queue Abstract Data Type The queue supports two fundamental methods: - enqueue(o): Insert object o at the rear of the queue Input: Object; Output: none - dequeue(): Remove the object from the front of the queue and return it; an error occurs if the queue is empty Input: none; Output: Object These support methods should also be defined: - size(): Return the number of objects in the queue Input: none; Output: integer - isempty(): Return a boolean value that indicates whether the queue is empty Input: none; Output: boolean - front(): Return, but do not remove, the front object in the queue; an error occurs if the queue is empty Input: none; Output: Object 14

An Array-Based Queue Create a queue using an array in a circular fashion A maximum size N is specified, e.g. N = 1,000. The queue consists of an N-element array Q and two integer variables: - f, index of the front element - r, index of the element after the rear one normal configuration Q... 0 1 2 f wrapped around configuration r N 1 Q 0 1 2 r f... N 1 what does f=r mean? 15

An Array-Based Queue (contd.) Pseudo-Code (contd.) Algorithm size(): return (N - f + r) mod N Algorithm isempty(): return (f = r) Algorithm front(): if isempty() then throw a QueueEmptyException return Q[f] Algorithm dequeue(): if isempty() then throw a QueueEmptyException temp Q[f] Q[f] null f (f + 1) mod N return temp Algorithm enqueue(o): if size = N - 1 then throw a QueueFullException Q[r] o r (r +1) mod N 16

Implementing a Queue with a Singly Linked List nodes connected in a chain by links head tail Rome Seattle Toronto the head of the list is the front of the queue, the tail of the list is the rear of the queue why not the opposite? 17

Removing at the Head head tail Baltimore Rome Seattle Toronto advance head reference head tail Baltimore Rome Seattle Toronto inserting at the head is just as easy 18

create a new node head tail Inserting at the Tail Rome Seattle Toronto Zurich chain it and move the tail reference head tail Rome Seattle Toronto Zurich how about removing at the tail? 19

Double-Ended Queues Adouble-ended queue, or deque, supports insertion and deletion from the front and back. The Deque Abstract Data Type - insertfirst(e): Insert e at the deginning of deque. Input: Object; Output: none - insertlast(e): Insert e at end of deque Input: Object; Output: none - removefirst(): Removes and returns first element Input: none; Output: Object - removelast(): Removes and returns last element Input: none; Output: Object Additionally supported methods include: - first() - last() - size() - isempty() 20

Implementing Stacks and Queues with Deques Stacks with Deques: Stack Method size() isempty() top() push(e) pop() Deque Implementation size() isempty() last() insertlast(e) removelast() Queues with Deques: Queue Method size() isempty() front() enqueue() dequeue() Deque Implementation size() isempty() first() insertlast(e) removefirst() 21

The Adaptor Pattern Using a deque to implement a stack or queue is an example of the adaptor pattern. Adaptor patterns implement a class by using methods of another class In general, adaptor classes specialize general classes Two such applications: - Specialize a general class by changing some methods. Ex: implementing a stack with a deque. - Specialize the types of objects used by a general class. Ex: Defining an IntegerArrayStack class that adapts ArrayStack to only store integers. 22

Implementing Deques with Doubly Linked Lists Deletions at the tail of a singly linked list cannot be done in constant time. To implement a deque, we use a doubly linked list. with special header and trailer nodes. header trailer Baltimore New York Providence A node of a doubly linked list has a next and a prev link. It supports the following methods: - setelement(object e) - setnext(object newnext) - setprev(object newprev) - getelement() - getnext() - getprev() By using a doubly linked list to, all the methods of a deque have constant (that is, O(1)) running time. 23

Implementing Deques with Doubly Linked Lists (cont.) When implementing a doubly linked lists, we add two special nodes to the ends of the lists: the header and trailer nodes. - The header node goes before the first list element. It has a valid next link but a null prev link. - The trailer node goes after the last element. It has a valid prev reference but a null next reference. The header and trailer nodes are sentinel or dummy nodes because they do not store elements. Here s a diagram of our doubly linked list: header trailer Baltimore New York Providence 24

Implementing Deques with Doubly Linked Lists (cont.) Let s look at some code for removelast() public class MyDeque implements Deque{ DLNode header_, trailer_; int size_;... public Object removelast() throws DequeEmptyException{ if(isempty()) throw new DequeEmptyException( Ilegal removal request. ); DLNode last = trailer_.getprev(); Object o = last.getelement(); DLNode secondtolast = last.getprev(); trailer_.setprev(secondtolast); secondtolast.setnext(trailer_); size_ --; return o; }... } 25

Implementing Deques with Doubly Linked Lists (cont.) Here s a visualization of the code for removelast(). header secondtolast last trailer Baltimore New York Providence San Francisco last header secondtolast trailer Baltimore New York Providence San Francisco header trailer Baltimore New York Providence 26

A Stock Analysis Applet The span of a stock s price on a certain day, d,isthe maximum number of consecutive days (up to the current day) the price of the stock has been less than or equal to its price on d. Below, let p i and s i be the span on day i s 0 =1 s 6 =6 s 1 =1 s 3 =2 s 5 =4 s 2 =1 s 4 =1 p 0 p 1 p 2 p 3 p 4 p 5 p 6 27

A Case Study: A Stock Analysis Applet (cont.) Quadratic-Time Algorithm: We can find a straightforward way to compute the span of a stock on a given day for n days: Algorithm computespans1(p): Input: An n-element array P of numbers Output: An n-element array S of numbers such that S[i] is the span of the stock on day i. Let S be an array of n numbers for i=0 to n-1 do k 0 done false repeat if P[i-k] P[i] then k k+1 else done true until (k=i) or done S[i] k return array S The running time of this algorithm is (ugh!) O(n 2 ). Why? 28

A Case Study: A Stock Analysis Applet (cont.) Linear-Time Algorithm: We see that si on day i can be easily computed if we know the closest day preceding i, such that the price is greater than on that day than the price on day i. If such a day exists let s call it h(i). The span is now defined as si = i -h(i) p 0 p 1 p 2 p 3 p 4 p 5 p 6 The arrows point to h(i) 29

A Case Study: A Stock Analysis Applet (cont.) The code for our new algorithm: Algorithm computespan2(p): Input: An n-element array P of numbers Output: An n-element array S of numbers such that S[i] is the span of the stock on day i. Let S be an array of n numbers and D an empty stack for i=0 to n-1 do done false while not(d.isempty() or done) do if P[i] P[D.top()] then D.pop() else done true if D.isEmpty() then h -1 else h D.top() S[i] i-h D.push(i) return array S Let s analysize computespan2 s run time... 30

A Case Study: A Stock Analysis Applet (cont.) The total running time of the while loop is n 1 O ( t i + 1) i = 0 However, once an element is popped off the stack, it is never pushed on again. Therefore: n 1 i = 0 The total time spent in the while loop is O(n). t i The run time of computespan2 is the summ of three O(n) terms. Thus the run time of computespan2 is O(n). n 31