Basic Data Structures

Similar documents
Basic Data Structures 1 / 24

Priority Queues 1 / 15

Algorithms. Algorithms 1.3 STACKS AND QUEUES. stacks resizing arrays queues generics iterators applications ROBERT SEDGEWICK KEVIN WAYNE.

CMSC 132, Object-Oriented Programming II Summer Lecture 9:

Symbol Tables 1 / 15

CMSC 132: Object-Oriented Programming II. Stack and Queue

Stacks and Queues. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

The Stack ADT. Stacks and Queues. Stack: Illustration. What is a Stack? Accessors top size isempty

JVM (java) compiler. A Java program is either a library of static methods (functions) or a data type definition

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle.

Project 2 (Deques and Randomized Queues)


What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

COMPUTER SCIENCE. Computer Science. 12. Stacks and Queues. Computer Science. An Interdisciplinary Approach. Section 4.3

Week 4 Stacks & Queues

14. Stacks and Queues

14. Stacks and Queues

14. Stacks and Queues

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011

Analysis of Algorithms 1 / 18

Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications. Is Polleverywhere working?

4.3 Stacks and Queues

CS24 Week 4 Lecture 2

Queues. Stacks and Queues

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11.

Lecture 2: Stacks and Queues

Building Java Programs

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

! Set of operations (add, remove, test if empty) on generic data. ! Intent is clear when we insert. ! Which item do we remove? Stack.

What is an algorithm?

Announcements Queues. Queues

1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures

CSE 143 SAMPLE MIDTERM

Stacks and Queues. Chapter Stacks

CPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues

CS61B Spring 2016 Guerrilla Section 2 Worksheet

Algorithms. Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications

== isn t always equal?

CS 216 Exam 1 Fall SOLUTION

CSC 1052 Algorithms & Data Structures II: Queues

Name CPTR246 Spring '17 (100 total points) Exam 3

4.3 Stacks and Queues. Stacks. Stacks and Queues. Stack API

CPSC 221: Algorithms and Data Structures ADTs, Stacks, and Queues

Data Abstraction and Specification of ADTs

CMP Points Total Midterm Spring Version (16 Points) Multiple Choice:

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

THE UNIVERSITY OF WESTERN AUSTRALIA

A queue is a linear collection whose elements are added on one end and removed from the other

Queues Fall 2018 Margaret Reid-Miller

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

csci 210: Data Structures Stacks and Queues

Stacks and Queues

CSE 373 Data Structures and Algorithms. Lecture 2: Queues

Introduction to Computing II (ITI 1121) Final Examination

All the above operations should be preferably implemented in O(1) time. End of the Queue. Front of the Queue. End Enqueue

COL106: Data Structures and Algorithms. Ragesh Jaiswal, IIT Delhi

Stacks and Queues. Gregory D. Weber. CSCI C243 Data Structures

CSE 143. Lecture 4: Stacks and Queues

COSC160: Data Structures: Lists and Queues. Jeremy Bolton, PhD Assistant Teaching Professor

CS61B Lecture #20: Trees. Last modified: Wed Oct 12 12:49: CS61B: Lecture #20 1

Lecture 3: Queues, Testing, and Working with Code

CS 251 Intermediate Programming Java I/O Streams

Stacks, Queues (cont d)

Searching Applications 1 / 18

Stacks and Queues. David Greenstein Monta Vista

Outline. 1 Hashing. 2 Separate-Chaining Symbol Table 2 / 13

Summer Final Exam Review Session August 5, 2009

Computer Science First Exams Pseudocode Standard Data Structures Examples of Pseudocode

Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays. queue. generics. applications. Stacks and queues

STACKS AND QUEUES. Problem Solving with Computers-II

Java classes cannot extend multiple superclasses (unlike Python) but classes can implement multiple interfaces.

The Java Collections Framework. Chapters 7.5

Java generics. h"p:// h"p://

INFO1x05 Tutorial 6. Exercise 1: Heaps and Priority Queues

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Examination Questions Midterm 1

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004)

Write a program to implement stack or any other data structure in Java ASSIGNMENT NO 15

ITI Introduction to Computing II

More Data Structures (Part 1) Stacks

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

(f) Given what we know about linked lists and arrays, when would we choose to use one data structure over the other?

Algorithms. Algorithms. Algorithms 1.3 BAGS, QUEUES, AND STACKS. stacks resizing arrays queues generics iterators applications

CS350: Data Structures Stacks

16-Dec-10. Collections & Data Structures ABSTRACTION VS. IMPLEMENTATION. Abstraction vs. Implementation

n Data structures that reflect a temporal relationship q order of removal based on order of insertion n We will consider:

Standard ADTs. Lecture 19 CS2110 Summer 2009

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12

Top of the Stack. Stack ADT

Lecture 4. The Java Collections Framework

final int a = 10; for(int i=0;i<a;i+=2) { for(int j=i;j<a;j++) { System.out.print("*"); } System.out.println(); }

Complexity, General. Standard approach: count the number of primitive operations executed.

Queues. Virtuelle Fachhochschule. Prof. Dr. Debora Weber-Wulff

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

CS 61B Spring 2017 Guerrilla Section 3 Solutions

CSC Java Programming, Fall Java Data Types and Control Constructs

IT 4043 Data Structures and Algorithms. Budditha Hettige Department of Computer Science

CS 221 Review. Mason Vail

Transcription:

Basic Data Structures

Some Java Preliminaries Generics (aka parametrized types) is a Java mechanism that enables the implementation of collection ADTs that can store any type of data Stack <String > s1 = new Stack <String >(); Stack <Date > s2 = new Stack <Date >(); s1. push (" Test "); s2. push ( new Date (3, 14, 1879)); String s = s1. pop (); Date d = s2.pop (); Since generics are reference types, Java allows generic code to be used with primitive types by automatically converting (auto boxing) them to their corresponding (wrapper) reference types and vice versa (auto unboxing) Stack <Integer > stack = new Stack <Integer >(); stack. push (42); // auto boxing ( int -> Integer ) int i = stack. pop (); // auto unboxing ( Integer -> int ) Iterable collections can be enumerated using foreach statement Bag <Integer > numbers = new Bag <Integer >();... for ( int x : numbers ) { StdOut. println (x); which (roughly) translates to Iterator <Integer > iter = numbers. iterator (); while ( iter. hasnext ()) { StdOut. println ( iter. next ());

Linked Lists A linked list is a recursive data structure that is either empty (null) or a reference to a node having a generic item and a reference to a linked list Node record private class Node { Item item ; // generic item Node next ; Traversal for ( Node x = first ; x!= null ; x = x. next ) { // do something with x. item.

Linked Lists Building a linked list Node first = new Node (); first. item = " to"; first to null Node second = new Node (); second. item = "be"; first. next = second ; first second to be null Node third = new Node (); third. item = " or"; second. next = third ; first second third to be or null

Linked Lists Insert at the beginning Node oldfirst = first ; first oldfirst to be or null first = new Node (); first. item = " not "; first oldfirst not null to be or null first. next = oldfirst ; first not to be or null

Linked Lists Remove from the beginning first = first. next ; first not to be or null first not to be or null

Linked Lists Insert at the end Node oldlast = last ; first oldlast last to be or null last = new Node (); last. item = " not "; first oldlast last to be or null not null oldlast. next = last ; first oldlast last to be or not null

Bags A Bag is an iterable collection that provides clients the ability to collect items method Bag<Item>() boolean isempty() int size() void add(item item) Iterator<Item> iterator() description construct an empty bag is the bag empty? number of items in the bag add item to the bag an iterator over the items in the bag

Bags Bag client import edu. princeton. cs. algs4. LinkedBag ; import edu. princeton. cs. algs4. StdIn ; import edu. princeton. cs. algs4. StdOut ; public class Stats { public static void main ( String [] args ) { LinkedBag <Double > numbers = new LinkedBag <Double >(); while (! StdIn. isempty ()) { numbers. add ( StdIn. readdouble ()); int N = numbers. size (); double sum = 0.0; for ( double x : numbers ) { sum += x; double mean = sum / N; sum = 0.0; for ( double x : numbers ) { sum += (x - mean ) * (x - mean ); double std = Math. sqrt ( sum / (N - 1)); StdOut. printf (" Mean : %.2 f\n", mean ); StdOut. printf (" Std dev : %.2 f\n", std ); $ java Stats 100 99 101 120 98 107 109 81 101 90 <ctrl -d> Mean : 100.60 Std dev : 10.51

Bags Bag implementation using a linked list package edu. princeton. cs. algs4 ; import java. util. Iterator ; import java. util. NoSuchElementException ; public class LinkedBag <Item > implements Iterable <Item > { private Node first ; private int N; private class Node { Item item ; Node next ; public LinkedBag () { first = null ; N = 0; public boolean isempty () { return first == null ; public int size () { return N; public void add ( Item item ) { Node oldfirst = first ; first = new Node (); first. item = item ; first. next = oldfirst ; N ++;

Bags public Iterator <Item > iterator () { return new ListIterator <Item >( first ); private class ListIterator <Item > implements Iterator <Item > { private Node current ; public ListIterator ( Node first ) { current = first ; public boolean hasnext () { return current!= null ; public Item next () { if (! hasnext ()) { throw new NoSuchElementException (); Item item = current. item ; current = current. next ; return item ;

Bags Bag implementation using a resizing array package edu. princeton. cs. algs4 ; import java. util. Iterator ; import java. util. NoSuchElementException ; public class ResizingArrayBag <Item > implements Iterable <Item > { private Item [] a; private int N; public ResizingArrayBag () { a = ( Item []) new Object [2]; N = 0; public boolean isempty () { return N == 0; public int size () { return N; private void resize ( int capacity ) { Item [] temp = ( Item []) new Object [ capacity ]; for ( int i = 0; i < N; i ++) { temp [i] = a[i]; a = temp ; public void add ( Item item ) { if (N == a. length ) { resize (2 * a. length ); a[n ++] = item ;

Bags public Iterator <Item > iterator () { return new ArrayIterator (); private class ArrayIterator implements Iterator <Item > { private int i; public ArrayIterator () { i = 0; public boolean hasnext () { return i < N; public Item next () { if (! hasnext ()) { throw new NoSuchElementException (); return a[i ++];

Queues A Queue is an iterable collection that is based on the first-in-first-out (FIFO) policy method Queue<Item>() boolean isempty() int size() void enqueue(item item) Item dequeue() Iterator<Item> iterator() description construct an empty queue is the queue empty? number of items in the queue add item to the queue remove the least recently added item an iterator over the items in the queue

Queues Queue client import edu. princeton. cs. algs4. LinkedQueue ; import edu. princeton. cs. algs4. StdIn ; import edu. princeton. cs. algs4. StdOut ; public class ReadInts { public static void main ( String [] args ) { LinkedQueue <Integer > q = new LinkedQueue <Integer >(); while (! StdIn. isempty ()) { q. enqueue ( StdIn. readint ()); for ( int i : q) { StdOut. println (i); $ java ReadInts 100 99 101 120 98 107 <ctrl -d> 100 99 101 120 98 107

Queues Queue implementation using a linked list package edu. princeton. cs. algs4 ; import java. util. Iterator ; import java. util. NoSuchElementException ; public class LinkedQueue <Item > implements Iterable <Item > { private int N; private Node first ; private Node last ; private class Node { Item item ; Node next ; public LinkedQueue () { first = null ; last = null ; N = 0; public boolean isempty () { return first == null ; public int size () { return N;

Queues public void enqueue ( Item item ) { Node oldlast = last ; last = new Node (); last. item = item ; last. next = null ; if ( isempty ()) { first = last ; else { oldlast. next = last ; N ++; public Item dequeue () { if ( isempty ()) { throw new NoSuchElementException (); Item item = first. item ; first = first. next ; N - -; if ( isempty ()) { last = null ; return item ; public Iterator <Item > iterator () { return new ListIterator <Item >( first );

Queues private class ListIterator <Item > implements Iterator <Item > { private Node current ; public ListIterator ( Node first ) { current = first ; public boolean hasnext () { return current!= null ; public Item next () { if (! hasnext ()) { throw new NoSuchElementException (); Item item = current. item ; current = current. next ; return item ;

Queues Queue implementation using a resizing array package edu. princeton. cs. algs4 ; import java. util. Iterator ; import java. util. NoSuchElementException ; public class ResizingArrayQueue <Item > implements Iterable <Item > { private Item [] q; private int N; private int first ; private int last ; public ResizingArrayQueue () { q = ( Item []) new Object [2]; N = 0; first = 0; last = 0; public boolean isempty () { return N == 0; public int size () { return N;

Queues private void resize ( int max ) { Item [] temp = ( Item []) new Object [ max ]; for ( int i = 0; i < N; i ++) { temp [i] = q[( first + i) % q. length ]; q = temp ; first = 0; last = N; public void enqueue ( Item item ) { if (N == q. length ) { resize (2 * q. length ); q[ last ++] = item ; if ( last == q. length ) { last = 0; N ++; public Item dequeue () { if ( isempty ()) { throw new NoSuchElementException (); Item item = q[ first ]; q[ first ] = null ; N - -; first ++; if ( first == q. length ) { first = 0; if (N > 0 && N == q. length / 4) { resize (q. length / 2); return item ;

Queues public Iterator <Item > iterator () { return new ArrayIterator (); private class ArrayIterator implements Iterator <Item > { private int i; public ArrayIterator () { i = 0; public boolean hasnext () { return i < N; public Item next () { if (! hasnext ()) { throw new NoSuchElementException (); Item item = q[( i + first ) % q. length ]; i ++; return item ;

Stacks A Stack is an iterable collection that is based on the last-in-first-out (LIFO) policy method Stack<Item>() boolean isempty() int size() void push(item item) Item peek() Item pop() Iterator<Item> iterator() description construct an empty stack is the stack empty? number of items in the stack add item to the stack most recently added item remove the most recently added item an iterator over the items in the stack

Stacks Stack client import edu. princeton. cs. algs4. LinkedStack ; import edu. princeton. cs. algs4. StdIn ; import edu. princeton. cs. algs4. StdOut ; public class Reverse { public static void main ( String [] args ) { LinkedStack <Integer > stack = new LinkedStack <Integer >(); while (! StdIn. isempty ()) { stack. push ( StdIn. readint ()); for ( int i : stack ) { StdOut. println (i); $ java Reverse 1 2 3 4 5 6 <ctrl -d> 6 5 4 3 2 1

Stacks Stack implementation using a linked list package edu. princeton. cs. algs4 ; import java. util. Iterator ; import java. util. NoSuchElementException ; public class LinkedStack <Item > implements Iterable <Item > { private int N; private Node first ; private class Node { Item item ; Node next ; public LinkedStack () { first = null ; N = 0; public boolean isempty () { return first == null ; public int size () { return N; public void push ( Item item ) { Node oldfirst = first ; first = new Node (); first. item = item ; first. next = oldfirst ; N ++;

Stacks public Item peek () { if ( isempty ()) { throw new NoSuchElementException (); return first. item ; public Item pop () { if ( isempty ()) { throw new NoSuchElementException (); Item item = first. item ; first = first. next ; N - -; return item ; public Iterator <Item > iterator () { return new ListIterator <Item >( first ); private class ListIterator <Item > implements Iterator <Item > { private Node current ; public ListIterator ( Node first ) { current = first ; public boolean hasnext () { return current!= null ; public Item next () { if (! hasnext ()) { throw new NoSuchElementException (); Item item = current. item ; current = current. next ; return item ;

Stacks Stack implementation using a resizing array package edu. princeton. cs. algs4 ; import java. util. Iterator ; import java. util. NoSuchElementException ; public class ResizingArrayStack <Item > implements Iterable <Item > { private Item [] a; private int N; public ResizingArrayStack () { a = ( Item []) new Object [2]; N = 0; public boolean isempty () { return N == 0; public int size () { return N; private void resize ( int capacity ) { Item [] temp = ( Item []) new Object [ capacity ]; for ( int i = 0; i < N; i ++) { temp [i] = a[i]; a = temp ; public void push ( Item item ) { if (N == a. length ) { resize (2 * a. length ); a[n ++] = item ;

Stacks public Item pop () { if ( isempty ()) { throw new NoSuchElementException (); Item item = a[n - 1]; a[n - 1] = null ; N - -; if (N > 0 && N == a. length / 4) { resize (a. length / 2); return item ; public Item peek () { if ( isempty ()) { throw new NoSuchElementException (); return a[n - 1]; public Iterator <Item > iterator () { return new ReverseArrayIterator (); private class ReverseArrayIterator implements Iterator <Item > { private int i; public ReverseArrayIterator () { i = N - 1; public boolean hasnext () { return i >= 0; public Item next () { if (! hasnext ()) { throw new NoSuchElementException (); return a[i - -];

Performance Characteristics In the linked-list implementations of the Bag, Queue, and Stack APIs, all operations take constant time in the worst case In the resizing-array implementations of the Bag, Queue, and Stack APIs, the amortized cost for any sequence of operations is constant in the worst case