Lists Weiss sec. 6.5 (sort of) ch. 17 (sort of). Arrays Random access a[38] gets 39 th element But fixed size, specified at construction e.g. pickLineFromFile(

Slides:



Advertisements
Similar presentations
Linked Lists Geletaw S..
Advertisements

Lists CS 3358.
Linked Lists Chapter 4.
DATA STRUCTURES USING C++ Chapter 5
Linked Lists Linear collections.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
1 Queues (5.2) CSE 2011 Winter May Announcements York Programming Contest Link also available from.
Variations on Linked Lists Ellen Walker CPSC 201 Data Structures Hiram College.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
LISTS & TREES Lecture 8 CS2110 – Fall List Overview 2  Purpose  Maintain an ordered set of elements (with possible duplication)  Common operations.
1 Chapter 3 Arrays, Linked Lists, and Recursion. 2 Static vs. Dynamic Structures A static data structure has a fixed size This meaning is different than.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
1 Lists. 2 Overview Arrays –Random access: –Fixed size: cannot grow on demand after creation:  Characteristics of some applications: –do not need random.
© 2006 Pearson Addison-Wesley. All rights reserved5 A-1 Chapter 5 Linked Lists.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 17 Linked.
Lecture 6: Linked Lists Linked lists Insert Delete Lookup Doubly-linked lists.
Linked Lists part II. Linked Lists A linked list is a dynamic data structure consisting of nodes and links: 627 start 8 This symbol indicates a null reference.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Linked List and Namespace ~ include dynamic objects.
Trees Weiss sec (preview) ch. 18 (sort of).
Chapter 3: Arrays, Linked Lists, and Recursion
Stacks, Queues, and Deques
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
2 Preliminaries Options for implementing an ADT List Array has a fixed size Data must be shifted during insertions and deletions Linked list is able to.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
Lists ADT (brief intro):  Abstract Data Type  A DESCRIPTION of a data type  The data type can be anything: lists, sets, trees, stacks, etc.  What.
CSE 131 Computer Science 1 Module 9: Linked Lists Using references to link objects Basic operations on linked lists Implementing a linked list of integers.
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
LISTS Slides of K. Birman, Cornell University. List Overview 2  Purpose  Maintain an ordered collection of elements (with possible duplication)  Common.
Chapter 1 Object Oriented Programming. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Dynamic Array. An Array-Based Implementation - Summary Good things:  Fast, random access of elements  Very memory efficient, very little memory is required.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
LISTS Lecture 9 CS2110 – Fall Time spent on A2 2  max: 25.4; avg: 5.2 hours, mean: 4.5 hours, min: 0.57 hours.
Section 4 Boxing classes Boxing classes Array initialization Array initialization Lists: recursion and iteration Lists: recursion and iteration.
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
Winter 2006CISC121 - Prof. McLeod1 Stuff Deadline for assn 3 extended to Monday, the 13 th. Please note that the testing class for assn 3 has changed.
Chapter 5 Linked Lists II
Linked Lists Chapter 4. Linked Structures: Motivations Arrays have fixed size –Problematic for data structures of arbitrary size Arrays order items physically.
1 Today’s Material List ADT –Definition List ADT Implementation: LinkedList.
Chapter 5 Linked Lists. © 2004 Pearson Addison-Wesley. All rights reserved 5 A-2 Preliminaries Options for implementing an ADT –Array Has a fixed size.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
Linked lists. Data structures to store a collection of items Data structures to store a collection of items are commonly used Typical operations on such.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
Data Structures Doubly and Circular Lists Lecture 07: Linked Lists
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
Question of the Day  What three letter word completes the first word and starts the second one: DON???CAR.
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
CS 46B: Introduction to Data Structures July 23 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
CompSci 100E 19.1 Getting in front  Suppose we want to add a new element  At the back of a string or an ArrayList or a …  At the front of a string.
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
CPS 100e 6.1 What’s the Difference Here? l How does find-a-track work? Fast forward?
LINKED LISTS.
CS1020 L AB 3 (L INKED L IST ) Problem 1: Balls Problem 2: Josephine Problem 3: Keyboard.
Data Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
Recursion Powerful Tool
An Array-Based Implementation of the ADT List
Review Array Array Elements Accessing array elements
LINKED LISTS CSCD Linked Lists.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
CS2013 Lecture 4 John Hurley Cal State LA.
Presentation transcript:

Lists Weiss sec. 6.5 (sort of) ch. 17 (sort of)

Arrays Random access a[38] gets 39 th element But fixed size, specified at construction e.g. pickLineFromFile( ) in Assignment01 One approach: java.util.ArrayList –Keep an array of objects as a private field –Similar to array of objects, but using get(…) and set(…) –Resizes on demand Maintain size and capacity >= size If ever capacity < size, then double capacity and copy elements –Efficient, usually

Lists A Different Approach Many applications don’t need fast random access: –grow and shrink on demand –fast access only to certain elements (e.g., the first one) Abstract Data Type List: –ordered sequence of “cells”, each containing an Object –first cell is accessible –given any cell, the next cell is accessible (if there is one) –Yes, this is smells inductive/recursive 1 st element 2 nd 3 rd n th … remaining elements

Implementing Using References ListCell Object elt ListCell next ‘a’ ListCell Object elt Object next ‘b’ ListCell Object elt ‘z’ null List alpha Note: member methods not shown getElt( ), setElt( ) getNext( ), setNext( ) etc.

Code public class ListCell { private Object elt; private ListCell next; public ListCell(Object first, ListCell rest) { elt = first; next = rest; } public Object getElt( ) { return elt; } // sometimes: car public ListCell getNext() { return next; } // sometimes: cdr public void setElt(Object first) { elt = first; } // sometimes: rplaca public void setNext(ListCell rest) { next = rest; } // sometimes: rplacd }

Building a List public static void main(String args[ ]) { Integer a = new Integer(25); Integer b = new Integer(-9); Integer c = new Integer(3); ListCell p = new ListCell(a, new ListCell(b, new ListCell(c, null)) ); } Resulting data structure?

Building a List: #2 public static void main(String args[ ]) { Integer a = new Integer(25); Integer b = new Integer(-9); Integer c = new Integer(3); ListCell p; p = new ListCell(a, null); p = new ListCell(b, p); p = new ListCell(c, p); } Resulting data structure?

Accessing List Elements p; // 1st element p.getNext(); // 2nd element p.getNext().getNext(); // 3rd element p.getNext().getNext().getNext(); // 4 th p.setElt(8); // set 1st p.getNext().getElt(); // get 2nd p.getNext().getNext().setNext(null); // chop p.getNext().getNext().getNext().getElt(); // crash: throws NullPointerException ListCell p 1525 Accessing n th cell requires following n pointers 125

Linear Search Want to see if list contains a particular item –compare using equals( ) Q: Why static? static boolean search(ListCell p, Object o) { for (ListCell curr = p; curr != null; curr = curr.getNext()) { if (curr.getElt().equals(o)) return true; } return false; // if loop drops out, object not found }

Subtle Version Don’t need local variable Q: What happens to the original list p? static boolean search(ListCell p, Object o) { for ( ; p != null; p = p.getNext()) { if (p.getElt().equals(o)) return true; } return false; // if loop drops out, object not found }

Recursive Version Recursive data structures call for recursive methods –sometimes We can do recursion/induction on lists, just as for natural numbers. Compare: –for (int i = 1; i <= n; i++) … –for (ListCell curr = p; cur!=null; curr = curr.getNext( )) … base case: solve for an empty list (or 1-element list) recursive case: solve for larger list by first removing first element and recursing, then obtaining solution for whole list

Recursive Code Note: clever use of || –recursive call to search(…) only happens if first clause evaluates to false static boolean search(ListCell p, Object o) { if (p == null) return false; else return p.getElt().equals(o) | | search(p.getNext(), o); }

Recursion Not Solution to Everything Reversing a list: Think: reversing a stack of papers static ListCell reverse(ListCell p) { ListCell r = null; for ( ; p != null; p = p.getNext()) r = new ListCell(p.getElt(), r); return r; }

Variations on Lists: Headers Adding a header –one instance of List, containing many ListCells –always exists, even when list is empty convenient place for list instance methods: –search, insert, delete, etc List head List head public class List { private ListCell head; public List(ListCell h) { head = h; } … getHead … setHead … }

Variations on Lists : Header With Tail Store other info in header as well –pointer to tail of list –length of list List head tail length3 List head tail length0

Insertion Using header with no tail pointer: others similar insertHead(Object o) List head List head public class List { public void insertHead(Object o) { head = new ListCell(o, head); } public void insertTail(Object o) { ListCell newcell = new ListCell(o, null); // will be at the tail if (head == null) { // special case: list was empty; new cell is the first and last ite m head = newcell; } else { // find tail cell, then add new cell to tail // note: this loop has no body; it stops with tail pointing to last i tem ListCell tail; for (tail = head; tail.getNext() != null; tail = tail.getNext()); tail.setNext(newcell); } } } ex: new List(null).insertHead(“Hello”);

Deleting Items: First Cell Cut cell out of list, return the element deleted One special case, one general case // delete first cell of a List, returns deleted element public Object deleteFirst() throws Exception { if (head == null) throw new Exception("delete from empty list"); else { ListCell old = head; head = head.getNext(); old.setNext(null); // a precaution return old.getElt(); } } on error: punt

Deleting Items: Last Cell Two cells may need to be affected: –last cell is removed, and returned (as before) –next-to-last cell now points to null Recursive approach –base case: empty list  error –base case: one element list  same as deleteFirst( ) –base case: two elements  head points to null head.next is removed, returned –recursive case: many elements  leave head alone remove last from remainder

Deleting Items: Last Cell public class List { public Object deleteLast_recursive() throws Exception { if (head == null) throw new Exception("delete from empty list"); else if (head.getNext() == null) { // base case: only one item in list return deleteFirst(); } else if (head.getNext().getNext() == null) { // base case: only two items in list ListCell second = head.getNext(); // will be deleted head.setNext(null); // first remains, but now points to nothing return second.getElt(); } else { // general case: leave head completely alone, delete last from tail // note: this is very subtle: depends on both base cases above! return new List(head.getNext()).deleteLast_recursive(); } } } Note: Why do we need “new List(…)”? Does it matter? Very subtle…

Deleting Items: Last Cell (iterative) Two cells may need to be affected: –last cell is removed, and returned (as before) –next-to-last cell now points to null Iterative approach: –Need two pointers scanning the list, in lock-step –current points to an element –scout points to the element after current –current will become the next-to-last element –scout will become the last element

Deleting Items: Last Cell (iterative) public Object deleteLast() throws Exception { if (head == null) throw new Exception("delete from empty list"); else if (head.getNext() == null) { // only one item ListCell oldcell = head; head = null; return oldcell.getElt(); } else { // general case: find last element (removed from list), and // also next-to-last element (update to point to nothing) ListCell current = head; // will be next-to-last element ListCell scout = current.getNext(); // always one ahead of current while (scout.getNext() != null) { current = current.getNext(); scout = current.getNext(); // always one ahead } // loop ends when scout points at last cell current.setNext(null); // current becomes the new last element return scout.getElt(); } }

Insert and Delete in the Middle Insert c just after cell p: “splicing in” –c now points to p.next –p now points to c Delete c, which is just after cell p: “splicing out” –p now points to c.next –c now points to null –will need two “cursors” as before, scanning in lock-step See code on web site

Lists So far: singly-linked lists Could also implement doubly-linked lists –Each cell maintains next and prev pointers –Many methods become much easier, faster, simpler –But… more heap space required prev 1 next prev 5 next prev 25 next prev 125 next

Moral Lists are not terribly complex But… lots of room for mistakes –manipulating head, next and prev references is error-prone –a source of many, many bugs in student programs Which is why… –we implement a good List class once –…and never again In practice (but not in school!): Strive to never implement something that was already implemented (by someone at least as smart as you).