Basic Data Structures 1 / 24

Similar documents
Basic Data Structures

Priority Queues 1 / 15

Symbol Tables 1 / 15

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

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

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

Analysis of Algorithms 1 / 18

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

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

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

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

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


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

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

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

Project 2 (Deques and Randomized Queues)

4.3 Stacks and Queues

Queues. Stacks and Queues

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

Building Java Programs

Lecture 2: Stacks and Queues

Searching Applications 1 / 18

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.

Stacks and Queues. Chapter Stacks

Announcements Queues. Queues

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

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

CSE 143 SAMPLE MIDTERM

CS61B Spring 2016 Guerrilla Section 2 Worksheet

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

CSC 1052 Algorithms & Data Structures II: Queues

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

CS24 Week 4 Lecture 2

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

Data Abstraction and Specification of ADTs

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

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

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

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.

What is an algorithm?

csci 210: Data Structures Stacks and Queues

Stacks and Queues

CSE 373 Data Structures and Algorithms. Lecture 2: Queues

== isn t always equal?

CS210 Study Guide Swami Iyer. 1 Programming Model (Algorithms 1.1) 2. 2 Data Abstraction (Algorithms 1.2) 4

CS 216 Exam 1 Fall SOLUTION

Introduction to Computing II (ITI 1121) Final Examination

The Java Collections Framework. Chapters 7.5

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

CSE 143. Lecture 4: Stacks and Queues

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

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

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

Stacks, Queues (cont d)

Lecture 3: Queues, Testing, and Working with Code

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

Stacks and Queues. David Greenstein Monta Vista

Lecture 4. The Java Collections Framework

Summer Final Exam Review Session August 5, 2009

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

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.

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

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

ITI Introduction to Computing II

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

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

CS 251 Intermediate Programming Java I/O Streams

Top of the Stack. Stack ADT

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

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

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(); }

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

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

Abstract Data Types. Abstract Data Types

Linked Structures. See Section 3.2 of the text.

Transcription:

Basic Data Structures 1 / 24

Outline 1 Some Java Preliminaries 2 Linked Lists 3 Bags 4 Queues 5 Stacks 6 Performance Characteristics 2 / 24

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 ()); 3 / 24

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. 4 / 24

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 5 / 24

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 6 / 24

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

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 8 / 24

Bags A Bag is an iterable collection that provides clients the ability to collect items Bag client method Bag<Item>() boolean isempty() int size() void add(item item) Iterator<Item> iterator() import edu. princeton.cs. algs4. LinkedBag ; import edu. princeton.cs. algs4. StdIn ; import edu. princeton.cs. algs4. StdOut ; 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 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 9 / 24

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 ++; 10 / 24

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 ; 11 / 24

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 ; 12 / 24

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 ++]; 13 / 24

Queues A Queue is an iterable collection that is based on the first-in-first-out (FIFO) policy Queue client method Queue<Item>() boolean isempty() int size() void enqueue(item item) Item dequeue() Iterator<Item> iterator() import edu. princeton.cs. algs4. LinkedQueue ; import edu. princeton.cs. algs4. StdIn ; import edu. princeton.cs. algs4. StdOut ; 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 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 14 / 24

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; 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 ++; 15 / 24

Queues 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 ); 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 ; 16 / 24

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; 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; 17 / 24

Queues 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 ; 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 ; 18 / 24

Stacks A Stack is an iterable collection that is based on the last-in-first-out (LIFO) policy Stack client method Stack<Item>() boolean isempty() int size() void push(item item) Item peek() Item pop() Iterator<Item> iterator() import edu. princeton.cs. algs4. LinkedStack ; import edu. princeton.cs. algs4. StdIn ; import edu. princeton.cs. algs4. StdOut ; 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 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 19 / 24

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 ++; 20 / 24

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 ; 21 / 24

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 ; 22 / 24

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 - -]; 23 / 24

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 24 / 24