CS 151. Linked Lists and Iterators, continued. Monday, October 1, 12

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

Data Structures and Algorithms

Data Structures and Algorithms Lists

LINKED DATA STRUCTURES

Introduction to Object-Oriented Programming

Lecture 12 Doubly Linked Lists (with Recursion)

D06 PROGRAMMING with JAVA

Programming with Data Structures

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

CmpSci 187: Programming with Data Structures Spring 2015

Project 4 DB A Simple database program

Analysis of a Search Algorithm

DATA STRUCTURE - STACK

Introduction to Programming System Design. CSCI 455x (4 Units)

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

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

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Sequences in the C++ STL

Stacks. Data Structures and Data Types. Collections

ADTs,, Arrays, Linked Lists

DATA STRUCTURES USING C

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Linked Lists: Implementation Sequences in the C++ STL

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

DATA STRUCTURE - QUEUE

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

CompSci-61B, Data Structures Final Exam

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Introduction to Stacks

Node-Based Structures Linked Lists: Implementation

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

STACKS,QUEUES, AND LINKED LISTS

Circular Linked List. Algorithms and Data Structures

Universidad Carlos III de Madrid

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

Class 32: The Java Collections Framework

Data Structures Fibonacci Heaps, Amortized Analysis

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

10CS35: Data Structures Using C

Singly linked lists (continued...)

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

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

Sequential Data Structures

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

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

Stacks. Linear data structures

Generic Types in Java. Example. Another Example. Type Casting. An Aside: Autoboxing 4/16/2013 GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK.

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.

Common Data Structures

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

Algorithms and Data Structures Written Exam Proposed SOLUTION

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

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

Unordered Linked Lists

PA2: Word Cloud (100 Points)

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

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

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

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

CMSC 202H. ArrayList, Multidimensional Arrays

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

1 Description of The Simpletron

JAVA COLLECTIONS FRAMEWORK

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:

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

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

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

Java Map and Set collections

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

Data Structures and Algorithms

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

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

Arrays. Introduction. Chapter 7

Computer Programming I

In this Chapter you ll learn:

Abstract Data Types. Chapter 2

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

10 Java API, Exceptions, and Collections

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

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Introduction to Java

Chapter 8: Bags and Sets

Decision-making Computer Science Lesson to Prepare for UIL Computer Science Contest

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

Ordered Lists and Binary Trees

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

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

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators

Iterators. Provides a way to access elements of an aggregate object sequentially without exposing its underlying representation.

BCS2B02: OOP Concepts and Data Structures Using C++

Data Structures in the Java API

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Transcription:

CS 151 Linked Lists and Iterators, continued 1

Announcements Prelab 4 due now. Reminder of the course s late policy: You are allowed to have 2 labs up to one day late. After that, up to 10% per day penalty is applied. When you DO use your late, let me know when you ve handed it in so that I can tell the graders to re-run their fetch script. But there is no need to ask permission from me individually. 2 2

Linked List Review Recall that a linked list is a data structure that represents a sequence of elements that are stored non-contiguously in memory. Supported Linked List Operations: void add( item, index ) -- add an item at the specified index item remove( index ) -- remove and return the item at the specified index int size() -- return the number of elements in the stack boolean isempty() -- return whether the stack is empty of any items void clear()/makeempty() -- clear all items from the stack We saw how to implement a linked list (using an inner Node class, that is, a Node class defined inside the LinkedList class) such that the size, isempty and makeempty methods are O(1), and the add and remove methods are O(n). 3 3

4 Doubly Linked List Review A doubly-linked list is a linked list where each node not only keeps track of the next element in the list, but also of the previous one. The supported operations are the same as for the linked list, but our nodes have two pointers (next and previous), and our list itself has two entry points, front and back. class DoublyLinkedList<T> { class Node<T> { private T data private Node<T> next private Node<T> prev public Node( T data, Node<T> next, Node<T> prev ) this.data = data this.next = next this.prev = prev public Node<T> getprev() return prev public void setprev( Node<T> next ) this.prev = prev... 4

Doubly Linked List Implementation On your prelab, you thought a bit about the add method: class DoublyLinkedList<T> { class Node<T> {... Node<T> front // points to the front of the list Node<T> back // points to the back of the list int size // the number of elements in the list void add( T item, int index ) { // What special cases must you test for? // Special case for size == 0? // Special case for index == 0? // Special case for index == size? // Special case for index == size-1? 5 5

Doubly Linked List Implementation On your prelab, you thought a bit about the add method: class DoublyLinkedList<T> { class Node<T> {... Node<T> front // points to the front of the list Node<T> back // points to the back of the list int size // the number of elements in the list void add( T item, int index ) { if( (index<0) (index>size) ) throw IndexOutOfBoundsExc. if( size == 0 ) front = back = new Node(item, null, null) else if( index == 0 ) front = new Node(item, front, null) front.next.prev = front else if( index == size ) back = new Node(item, null, back) back.prev.next = back else tmpnode = getnth( index-1 ) tmp.next.prev = new Node(item, tmp.next, tmp ) tmp.next = tmp.next.prev size++ 6 6

Remove will require similar modifications. Doubly Linked List Implementation A LL with a dummy node is a doubly LL such that there is always one unused dummy node at the front of the list so that you never have null pointers for the front and back list pointers. Adds and removes complexity. A circular LL is a doubly LL with only one pointer into the list, front, and the last node s next pointer is front, and front.prev = last node. I.e. forms a circle! In summary: doubly LL s add a bit more complexity to your code (more pointers) but they allow traversals in both directions adding to the front and back are now both O(1) operations removing from the front and back are now O(1) operations, too however add and remove are still O(n) when removing from the middle and that isn t going to go away, unfortunately you can get rid of some of the case-work with the pointers by using a dummy node, or a circular linked list, but they add their own cases, too... 7 7

8 Iterator Pattern An Iterator is a structure that allows you to step through it sequentially. The Iterator interface contains 3 methods: boolean hasnext() // return true if elements remain to iterate T next() // returns the next element, if none throw exc. void remove() // removes last element returned by next() You ve used iterators, for example, a Scanner is an iterator: Scanner input = new Scanner( new File( test1.txt ) ); while( input.hasnext() ) System.out.println( input.next() ) Each Iterator you create is keeping its own pointer into the relevant data sequence (in the case above, a file). If you make two Scanners, they have their own pointers and can iterate through the file at different rates. When you implement a data structure that stores sequential data, it is nice to provide an Iterator so that users can easily iterate through the data using this same code pattern (and they don t have to learn the data structure s terms) 8

Iterator Pattern // For ex, you may create an ArrayListIterator inside ArrayList: class MyArrayListIterator<T> implements Iterator<T> { private int index; // what index will you iterate next public MyArrayListIterator() { index = 0; // Initially you re at the start public boolean hasnext() { return (index < size); // You re not yet at the end public T next() { if( hasnext() ) { return get(index++); // increments index *after* get // this calls ArrayList s get(..) throw new NoSuchElementException(); public void remove() { throw new UnsupportedOperationException(); // not yet :-) 9 9

Iterator Pattern And now I want to use the ArrayListIterator to iterate over my array list... MyArrayList<String> mal = new MyArrayList<String>(); mal.add( Hello. ); mal.add( fuzzy ); // But how do I use my iterator? How do I even get my iterator? We should really have a method in the MyArrayList class that returns a MyArrayListIterator, so that I can get one easily! MyArrayListIterator<String> mali = mal.iterator(); while( mali.hasnext() ) System.out.println( mali.next() ) // Good... but there are still a few problems... // For one, can I see MyArrayListIterator from the outside? // And if these elements are iterable, shouldn t this kind of // method be standard? 10 10

Once you have an Iterator, it s useful to provide access to it! The Iterable interface has a factory method iterator() public Iterator<T> iterator() public class MyArrayList<T> extends AbstractList<T> implements Iterable<T> { T[] data; int size; // same as before... <class methods as before> Iterable interface You could modify your ArrayList class to implement Iterable<T> so that you can produce iterators to iterate over the elements of your arraylist. public Iterator<T> iterator() { return new MyArrayListIterator<T>(this); 11 11

In summary, if your class has iterable elements, you should Iterator Pattern 1. create an inner class that implements an Iterator<T>, to iterate over elements 2. have the data structure implement the Iterable<T> interface, which needs... 3. implement the iterator() method in the DS to return instance of your Iterator If you do this, then code like this will work: MyArrayList<String> mal = new MyArrayList<String>(); /* Maybe add some stuff to mal so it s not totally boring... */ Iterator<String> it = mal.iterator() // get the iterator while( it.hasnext() ) System.out.println( it.next() ) // print out all elements /* Even better, you can use the fancy for loops */ for( String s : mal ) System.out.println( s ) 12 12