! stack, queue, priority queue, dictionary, sequence, set e.g., a Stack is a list implements a LIFO policy on additions/deletions.



Similar documents
CmpSci 187: Programming with Data Structures Spring 2015

Analysis of a Search Algorithm

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

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

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

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

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

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

Common Data Structures

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

Programming with Data Structures

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

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

DATA STRUCTURES USING C

Algorithms and Data Structures

Linked Lists Linked Lists, Queues, and Stacks

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

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

Data Structures and Data Manipulation

Chapter 3: Restricted Structures Page 1

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

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

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

Sequential Data Structures

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

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

STACKS,QUEUES, AND LINKED LISTS

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

Java Software Structures


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.

Introduction to Data Structures and Algorithms

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

Unordered Linked Lists

Cpt S 223. School of EECS, WSU

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

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

DATA STRUCTURE - QUEUE

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

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

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

DATA STRUCTURE - STACK

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

Data Structures and Algorithms Stacks and Queues

LINKED DATA STRUCTURES

PES Institute of Technology-BSC QUESTION BANK

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

Universidad Carlos III de Madrid

Data Structures. Jaehyun Park. CS 97SI Stanford University. June 29, 2015

Abstract Data Types. Chapter 2

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

Data Structures and Algorithms Lists

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

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

Binary Heap Algorithms

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

Big O and Limits Abstract Data Types Data Structure Grand Tour.

Module 2 Stacks and Queues: Abstract Data Types

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

14 Stacks, Queues, And Linked Lists

Stacks. Linear data structures

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

Algorithms and Data Structures Written Exam Proposed SOLUTION

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

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

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 Algorithms

COMPUTER SCIENCE. Paper 1 (THEORY)

Data Structure [Question Bank]

Linked List as an ADT (cont d.)

Data Structures In Java

Chapter 14 The Binary Search Tree

CMSC 202H. ArrayList, Multidimensional Arrays

How To Write A Report In Xbarl

10CS35: Data Structures Using C

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!

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

Data Structures in the Java API

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

1 Abstract Data Types Information Hiding

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

- 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

B-Trees. Algorithms and data structures for external memory as opposed to the main memory B-Trees. B -trees

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

7.1 Our Current Model

Introduction to Data Structures

TREE BASIC TERMINOLOGIES

Introduction to Stacks

Stacks. Data Structures and Data Types. Collections

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

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

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Heaps & Priority Queues in the C++ STL 2-3 Trees

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

Chapter 8: Bags and Sets

Section IV.1: Recursive Algorithms and Recursion Trees

Data Structures and Algorithms

Data Structures, Practice Homework 2, with Solutions (not to be handed in)

D06 PROGRAMMING with JAVA

Transcription:

Abstract Data Types and Data Structures Often, these terms are used as synonyms. But it s better to think of them this way: ADTs and Data Structures An Abstract Data Type (ADT) represents a particular set of behaviours.! You can formally define (i.e., usin mathematical loic) what an ADT is/does. Some common ADTs that all trained prorammers know about:! stack, queue, priority queue, dictionary, sequence, set e.., a Stack is a list implements a LIFO policy on additions/deletions. Some common data structures used to implement those ADTS: A data structure is more concrete. Typically, it is a technique or stratey for implementin an ADT.! Use a linked list or an array to implement a stack class. Goin one level lower, we et into particulars of prorammin lanuaes and libraries! Use java.lan.vector or java.util.stack or a C++ library from STL.! array, linked list, hash table (open, closed, circular hashin)! trees (binary search trees, heaps, AVL trees, 2-3 trees, tries, red/black trees, B-trees) We ll discuss these is some detail. CS211 DATASTRUCTURESANDADTS 1 CS211 DATASTRUCTURESANDADTS 2 Revisitin the Stack What s Wron with this Picture? Recall our friend the stack, as implemented by an array. There s somethin unsatisfyin about this implementation. class stack f private int maxsize, top = -1; public static final int DefaultMaxSize = 100; private Object [] store;. public stack () f maxsize = DefaultMaxSize; public stack (int desiredmaxsize) f maxsize = desiredmaxsize; public void push (Object newval) f if (top < maxsize -1) f top++; store[top]=newval; else f System.err.println ("Sorry, stack is full."); We have to state, in advance, exactly how many elements we will need. [Or just use the provided default of 100]! If we o over that number of elements at any one point in time, the stack stops workin.! If we use a bi desiredmaxsize, then we waste space most of the time. [What if we need several stacks?] This approach uses a static approach to resource allocation:! We have to decide before creatin the object what its size will be.! We are not allowed to chane the size durin its lifetime. Yes, all resources are ultimately finite. But we would like a little more flexibility and reasonable use of resources. CS211 STACKSANDQUEUES 1 CS211 STACKSANDQUEUES 2

A Linked List Approach A Dynamic Approach to Resource Allocation me ray d oh What if we could desin a stack that used exactly enouh storae at any iven time? top! Sure we will run out of space eventually if we keep addin elements, but only if we really have to, i.e., only if the stack ets really hue.! What are the tradeoffs? Are there any disadvantaes? Dyanamically allocated structures can row and shrink as needed throuhout their lifetime. The stack is a set of nodes linked toether.! Each node has a value plus a link variable (a reference to another node).! The value could be a simple value (e.., an int), a set of values, or a reference to another object (e.., an employee record). When you want to push a new value: A common yin-yan in CS in static vs. dynamic allocation. 1. Create a new node via new. 2. Set the value of the new node. 3. Set its link field to point to the previous top node. 4. Reset top to point to the new node. CS211 STACKSANDQUEUES 3 CS211 STACKSANDQUEUES 4 public interface Stack f public abstract void push (Object element); public abstract Object pop (); public abstract boolean isempty (); public abstract int size (); class Node f // Use packae-level visibility. Object value; Node next; public Node (Object value, Node next) f this.next = next; this.value = value; public class LinkedStack implements Stack f private int numelements; private Node ; public LinkedStack () f numelements = 0; = null; // Still inside LinkedStack... public Object pop () f Object returnval; if (numelements > 0) f returnval =.value; =.next; numelements--; else f System.out.println ("Sorry, stack is empty."); returnval = null; return returnval; public boolean isempty () f return numelements == 0; public int size () f return numelements; public void push (Object element) f Node newnode = new Node (element, ); = newnode; numelements++; CS211 STACKSANDQUEUES 5 CS211 STACKSANDQUEUES 6

For completeness, here is the array implementation restated slihtly as implementin the Stack interface: // Still inside LinkedStack... public static void main (Strin [] ars) f LinkedStack s1 = new LinkedStack(); s1.push ("hello"); s1.push ("there"); s1.push ("world"); System.out.println ("There are now " + s1.size() + " elements."); Strin s; s = (Strin) s1.pop(); System.out.println ("Popped: " + s); s = (Strin) s1.pop(); System.out.println ("Popped: " + s); s = (Strin) s1.pop(); System.out.println ("Popped: " + s); s = (Strin) s1.pop(); System.out.println ("Should be empty now."); public class ArrayStack implements Stack f private int maxsize; public static final int DefaultMaxSize = 100; private int top = -1; private Object [] store; public ArrayStack () f maxsize = DefaultMaxSize; public ArrayStack (int desiredmaxsize) f maxsize = desiredmaxsize; public void push (Object newval) f if (top < maxsize -1) f top++; store[top]=newval; else f System.err.println ("Sorry, stack is full."); CS211 STACKSANDQUEUES 7 CS211 STACKSANDQUEUES 8 // Still inside ArrayStack... public Object pop () f Object ans = null; if (top >= 0) f ans = store[top]; top--; else f System.err.println ("Sorry, stack is empty."); return ans; public boolean isempty () f return size() == 0; public int size () f return top + 1; Array vs. Linked List: Advantaes and Disadvantaes CS211 STACKSANDQUEUES 9 CS211 STACKSANDQUEUES 10

Another Stratey: Split the Difference 0 1 2 N-1 d oh ray me... la topchunk 0 1 2 N-1 tea doe??...?? Splittin the Difference : Advantaes and Disadvantaes top Keep a linked list of arrays (NodeChunks):! Each NodeChunk has a reference to the one before it.! Keep a reference to the top chunk, plus a top inteer that points to the top element in the top chunk. Must decide on a ood chunk size somehow.! Constructor ar and/or use a default size. CS211 STACKSANDQUEUES 11 CS211 STACKSANDQUEUES 12 Another ADT: The Queue Implementin a Queue with an Array A queue is a list that implements a FIFO (First In is the First Out) policy on insertions and deletions.! Can add elements only to the end of the list.! Can remove elements only from the front of the list. Add is called enter, enqueue, oradd Delete is called leave, dequeue, orremove Misc. extra methods: isempty, size 0 1 2 3 4 N-2 N-1?? ray me far?????? An ArrayQueue is trickier than an ArrayStack:... public interface Queue f public abstract void enter (Object element); public abstract Object leave (); public abstract boolean isempty (); public abstract int size ();! There are two pointers (int indexes into array) to keep track of.! When you run out of room, start over at the beinnin.! Of course, this static approach means you are limited to at most N elements in your queue at any iven moment. CS211 STACKSANDQUEUES 13 CS211 STACKSANDQUEUES 14

Implementin a Queue with an Array N-2...?? N-1 0???? 1 ray 2 me 3 far...?? 4 class ArrayQueue implements Queue f private int =0, =-1; private final int DefaultMaxSize = 100; private int maxsize, numelements = 0; private Object [] store; public ArrayQueue () f this.maxsize = DefaultMaxSize; store = new Object[maxSize]; public ArrayQueue (int maxsize) f this.maxsize = maxsize; store = new Object[maxSize]; Think of the array as a circle.! Use modular arithmetic to stay in the valid rane of indexes. To increment on an enter: = ( + 1) N; [Assumes there is space, i.e., element 0 is empty]! Items in the rane... are full.! Items in the rane +1... -1 are empty. public void enter (Object newelt) f if (size() < maxsize) f = ( + 1) maxsize; store[] = newelt; numelements++; else f System.err.println ("Sorry, queue is full."); CS211 STACKSANDQUEUES 15 CS211 STACKSANDQUEUES 16 public Object leave () f if (size() > 0) f Object ans = store[]; = ( + 1) maxsize; numelements--; return ans; else f System.err.println ("Sorry, queue is empty."); return null; public void print () f System.out.println("Printin the queue: " + size() + " elements."); int j = ; for (int i=0; i< size(); i++) f System.out.println (store[j]); j = (j + 1)maxSize; public int size () f return numelements; public boolean isempty () f return size() == 0; public static void main (Strin[] ars) f ArrayQueue q1 = new ArrayQueue(5); q1.enter ("do"); q1.enter ("re"); q1.enter ("mi"); q1.enter ("fa"); q1.enter ("so"); System.out.println ("Queue should be full now."); q1.enter ("la"); q1.enter ("la"); q1.enter ("ti"); q1.enter ("doh"); q1.enter ("ray"); q1.enter ("me"); q1.enter ("far"); q1.enter ("sew"); CS211 STACKSANDQUEUES 17 CS211 STACKSANDQUEUES 18

Implementin a Queue as a Linked List public class LinkedQueue implements Queue { private int numelements=0; private Node =null, =null; d oh ray me public void enter (Object element) { Node newnode = new Node (element, null); if (numelements == 0) { = newnode; else {.next = newnode; = newnode; numelements++; Pretty straihtforward to implement. Only caveat: watch out on enter! If queue empty, adjust to point to new node.! Otherwise reset.next to new node. Can also implement usin a NodeChunk [Each NodeChunk contains an array of values.] public Object leave () { Object returnval; if (numelements > 0) { returnval =.value; =.next; numelements--; else { System.out.println ("Sorry, queue is empty."); returnval = null; return returnval; // Obvious definitions for isempty and size omitted. CS211 STACKSANDQUEUES 19 CS211 STACKSANDQUEUES 20 This proram: Misc. Notes We have decided to declare the Node fields value and next as packae-level visible.! This means that other classes in the same packae, such as LinkedQueue, can directly manipulate the instance variables of each Node instance. Also, we can use more interestin objects than Strins and Inteers in our stacks and queues. class FiureQueueTest { public static void main (Strin[] ars) { Queue q = new LinkedQueue(); Circle c1, c2; c1 = new Circle(); c1.setsize(50); c1.setloc(25,30); c2 = new Circle(); Square s1 = new Square(); s1.setsize (75); q.enter(c1); q.enter(c2); q.enter(s1); while (!q.isempty()) { Fiure f = (Fiure) q.leave(); f.draw();! Could have a list of Fiures oremployeerecords Produces this output: Circle at x = 25 y = 30 with radius = 50 Circle at x = 0 y = 0 with radius = 0 Square at x = 0 y = 0 with width = 75 and heiht = 75 CS211 STACKSANDQUEUES 21 CS211 STACKSANDQUEUES 22