Arrays and Linked Lists. Johns Hopkins Department of Computer Science Course : Data Structures, Professor: Greg Hager

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

STACKS,QUEUES, AND LINKED LISTS

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

Universidad Carlos III de Madrid

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

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

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

Sequential Data Structures

Chapter 3: Restricted Structures Page 1

Data Structures and Algorithms Lists

Analysis of a Search Algorithm

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

Module 2 Stacks and Queues: Abstract Data Types

D06 PROGRAMMING with JAVA

Data Structures and Algorithms

CmpSci 187: Programming with Data Structures Spring 2015

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

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!

Cpt S 223. School of EECS, WSU

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

Programming with Data Structures

Common Data Structures

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

Linked Lists Linked Lists, Queues, and Stacks

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

Data Structures in the Java API

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

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

10CS35: Data Structures Using C

DATA STRUCTURES USING C

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

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

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

ADTs,, Arrays, Linked Lists

Data Structures and Algorithms Stacks and Queues

DATA STRUCTURE - QUEUE

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

Node-Based Structures Linked Lists: Implementation

PES Institute of Technology-BSC QUESTION BANK

Data Structures and Algorithms

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

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

Algorithms and Data Structures

DATA STRUCTURE - STACK

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

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

Unordered Linked Lists

Estrutura com iterador-1

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

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

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

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

Chapter 8: Bags and Sets

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

Introduction to Data Structures and Algorithms

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

LINKED DATA STRUCTURES

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

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

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

14 Stacks, Queues, And Linked Lists

Sequences in the C++ STL

7.1 Our Current Model

Linked Lists: Implementation Sequences in the C++ STL

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

Linked List as an ADT (cont d.)

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

Algorithms and Data Structures

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.

Stacks. Data Structures and Data Types. Collections

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

Introduction to Data Structures

Java Interview Questions and Answers

PROGRAMMING CONCEPTS AND EMBEDDED PROGRAMMING IN C, C++ and JAVA: Lesson-4: Data Structures: Stacks

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

Abstract Data Types. Chapter 2

Introduction to Stacks

Data Structures UNIT III. Model Question Answer

Circular Linked List. Algorithms and Data Structures

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

Stacks. Linear data structures

\Mankinds's progress is measured by the number of. Elementary data structures such as stacks, queues,

Singly linked lists (continued...)

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

Introduction to Object-Oriented Programming

Data Structure [Question Bank]

Algorithms and Abstract Data Types

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

CompSci-61B, Data Structures Final Exam

CMSC 202H. ArrayList, Multidimensional Arrays

Class 32: The Java Collections Framework

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

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

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

CSC 551: Web Programming. Fall 2001

Data Structures Fibonacci Heaps, Amortized Analysis

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

Lecture 12 Doubly Linked Lists (with Recursion)

Transcription:

Arrays and Linked Lists

Value vs. Reference Variables Value i 10 j Reference 10 new performs dynamic memory allocation int i=10; int[] j = new int[1]; j[0] = 10; Or int[] j = {10}; Variables of primitive types are value variables Variables of arrays and classes are reference variables Reference variables are a safer form of pointers (In C++, you can choose)

A Review of References Recall that all objects in Java are really references, I.e. what happens when I do MyObject x = new MyObject(a,b,c); MyObject y = x; MyFunction(y); x = new MyObject;

Arrays Refer to several values of same type Example: int[] myarray = new int[20]; Length field holds allocated number of elements myarray.length == 20 Indexed from 0..length-1 bounds checked dynamically Initialized manually or in declaration int[] myarray2 = {18, 36}; 18 36 myarray2 [0] [1]

java.util.arrays Predefined set of static methods operating on arrays equals(a,b) fill(a,x) sort(a) tostring(a)

2D (and higher D) Arrays May be allocated at once for rectangles int[][] i = new int[12][15]; Or deal with 1 dimension at a time int[][] i = new int[10][]; for (int j=0; j<10; j++) i[j] = new int[2*j + 1]; Note: multidimensional arrays appear as arrays of arrays e.g. i[3].length = 15 and i.length = 12;

Non-rectangular 2D Array i

Abstract Data Types Ideally, a data type can be described only in terms of operations and how they act, not in terms of how it is actually implemented or represented. This allows us to prove properties of the data type which may be useful for testing, implementation, optimization...

An Example: An Abstract Stack Basic rules: 1. There is a unique constant E (empty stack) 2. There are functions Push and Pop with rules 1. x.push(x.pop()) = x 2. x.pop(x.push(z)) = z 3. E.Pop() = error

List ADT What are the operations on a list of objects: print clear insert (where?) remove (what?) find access the kth element

A Warmup: Array Implementation How long do these take on an array-based implementation? print clear insert front rear at element remove at index find index of element access the kth element

The Idea of Linked List Singly linked lists Doubly linked lists Circular lists

Singly Linked List Node // Without generics. public class Node{ private Object element; private Node next; public Node(Object e, Node n) { element = e; next = n; } public Object getelement() { return element;} public Object setelement(ne) {element = ne;} public Node getnext() { return next;} public Node setnext(node nn) {next = nn;} }

SL List Implementation How long do these take on an singly-linked list-based implementation? print clear insert front rear at element remove at index find index of element access the kth element

Doubly Linked Lists The limitation of the singly linked lists stems from the fact we cannot look back Doubly linked lists overcome this problem With doubly linked lists, it is inconvenient to have an asymmetry at the beginning and end of the list. Sentinels are dummy nodes that do not hold data, but regularize the computation

Generic Doubly Linked List Node public class DNode<T> { private T element; private DNode<T> next, prev; public DNode(T e, DNode<T> n, DNode<T> p) { element = e; next = n; prev = p } }

Doubly Linked List Implementation public class MyList<T> { protected int numelts=0; protected Dnode<T> header, trailer; MyList () { header = new Dnode<T>(null,null,null); trailer = new Dnode<T>(null, header, null); header.setnext(trailer); } public Dnode<T> getprev(dnode<t> v) throws IllegalArgumentException { if (v == header) throw new IllegalArgumentException( At header ); return v.getprev(); } public Dnode<T> addbefore(dnode<t> p, Dnode<T> newnode) throws... { numelts++; newnode.setprev(p.getprev()); p.getprev().setnext(newnode); p.setprev(newnode); newnode.setnext(p); return newnode; } }

Exceptions Language-level support for managing run-time errors You can define your own exception classes Methods declare which exceptions they might possibly throw Calling methods either catch these exceptions or pass them up the call stack

Throw public void mymethod() throws BadThingHappened {... if (somecondition) throw new BadThingHappened;... } try... mymethod()... catch (BadThingHappened BTH) block catch (exceptiontype id) block finally block // ALWAYS executed!!

Removing public void remove(dnode v) { DNode u = getprev(v); DNode w = getnext(v); } w.setprev(u); u.setnext(w); v.setprev(null); v.setprev(null); size--;

DL List Implementation How long do these take on an doubly-linked list-based implementation? print clear insert front rear at element remove at index find index of element access the kth element

Java Collections Framework Collection: Any collection of objects; extends iterable and thus permits iteration with iterator() method Iterator: Basic iterator ADT List: Extends collection to include ArrayList and LinkedList; supports ListIterator (modification) ListIterator: Forward/backward and modification Stack: Add and remove from front Queue: Add to end, take from front All in java.util

Iterators Once we have a linear data structure, a natural model of computation is iteration An iterator abstracts this idea from the underlying data storage format! public interface Iterator<E> {!!public boolean hasnext();!!public E next();!!void remove( ); // last item return by next! }

Iterators Each class using an iterator can support Iterable<E>! public interface Iterable<E> {!!// return an iterator object!!public java.util.iterator<e> iterator();! }!!!

The Collection Interface In Java.util public interface Iterator<AnyType> { boolean hasnext( ); AnyType next( ); void remove( ); // last item returned by next } public interface Collection<AnyType> extends Iterable <AnyType> { int size( ); boolean isempty( ); void clear ( ); boolean contains( AnyType x ); boolean add( AnyType x ); boolean remove( AnyType x ); java.util.iterator<anytype> iterator( ); }

Why Iterable? Allows the use of special : syntax public static <T> void print( Collection<T> c ) { for (T item : c) System.out.println( item ); } // VS public static <T> void print( Collection<T> c ) { Iterator<T> itr = c.iterator( ); while (itr.hasnext( )) { T item = itr.next( ); System.out.println( item ); } }

The Dangers of Iterators Iterators make sense if data structures are static while they are in use. What if the DS changes? Could make copy (O(n)) Positions continue to make sense (although difficult to guarantee behavior). In Java, the list iterator in Java does not expose a position concept --- iterators are invalidated if container is changed.

What is the problem here? for (Integer x : lst ) if (x % 2 == 0) lst.remove(x) FAILS! Iterator itr = lst.iterator(); while (itr.hasnext()) if (itr.next() % 2 == 0) itr.remove();

The List Interface public interface List<T> extends Collection<T> { T get (int i); T set (int i); void add (int i, T x); void remove (int i); ListIterator<AnyType listiterator(int pos); } public interface ListIterator<T> extends Iterator<T> { boolean hasprevious( ); T previous( ); void add (T x); void set (T x); } Implemented by ArrayList and LinkedList!

Example of ListIterator I start with: 8 3 5 6 4 and execute System.out.println( iter.next() ); iter.add( 1 ) ; System.out.println( iter.next( ) ); iter.remove ( ) ; System.out.println( iter.next( ) ); iter.set ( 7 ) ; System.out.println( iter.next( ) ); x.set(4,20); What is the result?

Take Care How long do each of these take with linked list or array? for (int i=0; i< N; i++)!!lst.add( i, i );!! for (int i=0; i< N; i++)!!lst.add(0, i);!! for (int i=0; i< lst.size(); i++)!!total += lst.get(i);!

Take Care int i = 0;! while (i < lst.size)!!if lst(get(i)) % 2 == 0!!!!lst.remove(i);!!else!!!i++;! for (Integer x : lst)!!if (x%2 == 0)!!!lst.remove(x);!! Iterator<Integer> itr = lst.iterator();! while (itr.hasnext( ))!!if (itr.next( ) % 2 == 0)!!!itr.remove();!

ArrayList class Things to note: outer vs. inner vs. nested class for iterator inner good if 1-1 association nested allows non-associated exception handling automatic sizing

LinkedList Class Note: The use of sentinel nodes Visibility of nested class members Use of modcount

Amortization Useful analysis tool When some calls are more expensive than others, average out the costs over the total number of calls After every n calls to add, 1 call takes O(n) instead of O(1) Averaged out over n calls, each call is still O(1)

Formal Amortization Analysis Assume each add( ) costs $1 in compute time Overcharge these add( ) operations charge $3 each store $2 in the bank for each operation Now when the extend happens, use money from the bank to pay for the copy operations We pay for all n operations using a constant cost for each operation implies O(n) total cost, or average of O(1) per operation

Analysis with Summations Work done in extend for n pushes: 1+2+4+8+ +n = log n i = 0 2 i = 2 logn+1 1 = 2 * 2 logn 1 = 2n 1 = O(n) for n pushes (this is a base 2 number with logn + 1 bits, all set to 1)

On to Stacks and Queues

What is a Stack? Stores a set of elements in a particular order Accessed in Last-In-First-Out (LIFO) fashion Real life examples: Pile of books PEZ dispenser Cup trays in cafeteria CS examples: program execution stack, parsing/ evaluating expressions

Stack Abstract Data Type push(o): insert o on top of stack pop( ): remove object from top of stack top( ): look at object on top of stack (but don t remove) size( ): number of objects on the stack isempty( ): does (size = = 0)?

An Example: Call Stack Frames

HP 3000 Minicomputer (RIP)

Stack Exception public class StackEmptyException!!!!!extends RuntimeException {!! public EmptyStackException(String err) {!!!super(err);! }! }!

Exceptions Language-level support for managing run-time errors You can define your own exception classes Methods declare which exceptions they might possibly throw Calling methods either catch these exceptions or pass them up the call stack

Throw public void mymethod() throws BadThingHappened {... if (somecondition) throw new BadThingHappened;... } try... mymethod()... catch (BadThingHappened BTH) block catch (exceptiontype id) block finally block // ALWAYS executed!!

A Java Interface for Stack ADT public interface Stack<T> {!!public int size();!!public boolean isempty();!!public T top() throws!!!stackemptyexception;!!public void push (T element);!!public T pop() throws!!!stackemptyexception;! }!

Linked List Stack Implementation Benefits Avoids maximum stack size restriction Only allocates memory for stack elements actually used How Allocate a node for each stack element Nodes are chained together by reference to next node in the chain

Linked List Node public class Node<E> {!!private E element;!!private Node next;!!public Node(E e, Node n) {!!!element = e; next = n; }!!public E getelement() { return element;}!!public Node<E> getnext() { return next;}!!public void setelement(e newe) {element = newe;}!!public void setnext(node<e> newn) {next = newn;}! }!

Linked List Stack Implementation public class LinkedStack<E> implements Stack<E> {!!private Node<E> top = null;!!private int size = 0;!!!public void push(e elem) {!!!Node<E> v = new Node<E>(elem,top);!!!top = v;!!!size++; }!!!public E pop() throws StackEmptyException {!!!if (isempty()) throw new!!stackemptyexception( empty );!!!E temp = top.getelement();!!!top = top.getnext();!!!size --;!!!return temp; }! }!

Array-based Stack Implementation Allocate array of some size Maximum # of elements in stack Bottom stack element stored at index 0 first index tells which element is the top increment first when element pushed, decrement when pop d

Array-based Implementation public class ArrayStack<T> implements Stack<T> {!!private T[] S;!!private int topindex = -1;!!!public ArrayStack(int cap) {!! capacity cap;!! S = (T[]) new Object[capacity];! }!!!

Array-based Implementation! public void push(t obj) throws StackFull {!!!if (size() == S.length)! throw new StackFullException( stack full );!!!S[++topIndex] = obj; }!!! public T pop() throws StackEmpty {!!!if (isempty())! throw new StackEmptyException( empty );!!!T elem = S[topIndex];! S[topIndex--] = null;!!!return elem; }!!

Analysis Each operation is O(1) running time Independent of number of items in stack push, pop, top, size, isempty Space can be O(n) or may be much more depends if n is known at initialization time

Analysis All stack functions still O(1) push, pop, top, size, isempty

Examples Reversing an Array Paren matching HTML tags postfix arithmetic Converting to postfix

What is a Queue Stores a set of elements in a particular order Accessed in First-In-First-Out (FIFO) fashion Real life examples: Waiting in line at cafeteria Waiting on hold for technical support CS Example: Buffered I/O

Queue ADT enqueue(o): Insert object o at rear of queue dequeue( ): remove object from front of queue size( ): number of elements isempty( ): size == 0? front( ): look at object at front of queue

Queue Interface in Java public interface Queue<E> {!!public int size();!!public boolean isempty();!!public E front() throws QueueEmptyException;!!public void enqueue (E element);!!public E dequeue() throws QueueEmptyException;! }!

Array-based Queue Implementation Array of fixed size Index array element for front and rear of queue Indices wrap around when they cross end of array

Array Queue Implementation public class ArrayQueue<E> implements Queue<E> {!!private E[] Q;!!private int size=0;!!private int front=0, rear = 0;!!public void enqueue(e o) {!!!if (size() == Q.length) throw!!new QueueFullException( full );!!!Q[rear] = o;!!!rear = (rear + 1) % Q.length; size++;!!}! public E dequeue() {!!!if (size() == 0) throw!!new QueueEmptyException( hungry );!!!E tmp = Q[front];!!!front = (front + 1) % Q.length; size--;!!!return tmp;!}!

List Queue Implementation Head and tail node references for front and rear of queue Insert at tail, remove from head Remove from tail too slow for singly linked list Updating tail reference with new tail takes full traversal So use tail of list for rear of queue

List Queue Implementation public class ListQueue<E> implements Queue<E> {!!private Node<E> head = null;!!private Node<E> tail = null;!!private int size = 0;!!...!!public void enqueue(e elem)!!!node<e> node = new Node<E>(E,null);!!!if (empty()) head=node;!!!else tail.setnext(node);!!!tail = node; size++;!!}!!!!public E dequeue() throws QueueEmptyException {!!!if (empty()) throw QueueEmptyException( grr );!! E tmp = head.getelement();!! head = head.getnext(); size--;!! if (empty()) tail = null;!! return tmp;! }!

Analysis All queue operations are O(1) size( ), isempty( ) enqueue( ), dequeue( ), front( )

Examples Round-robin scheduling Buffered I/O Email Printing...

Example: The JVM JVM divides memory into two parts: stack and heap Stack is used for procedure calls and static allocation Heap is used for dynamic allocation In addition, the JVM maintains a queue of active threads

Double-ended Queue Sometimes called deque (dek) Similar to stack and queue Allows insertion and removal at both ends of the queue Stack or queue is easily implemented using a deque

Deque ADT insertfirst(e) : insert element at front insertlast(e) : insert element at rear removefirst( ) : remove first element removelast( ) : remove element at rear first( ) : examine first element last( ) : examine last element size(e) : number of elements in deque isempty( ) : size == 0?

Summary 1. Basic data structures: arrays, singly linked lists, doubly linked lists 2. Iterators, Iterable, Collections, Lists 3. Stacks, Queues and their uses 4. Time-analysis of implementations