LISTS & TREES Lecture 8 CS2110 – Fall 2008. List Overview 2  Purpose  Maintain an ordered set of elements (with possible duplication)  Common operations.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Linked Lists Geletaw S..
Singly linked lists Doubly linked lists
Singly Linked Lists What is a singly-linked list? Why linked lists?
Stacks, Queues, and Linked Lists
Linked Lists.
Data Structures ADT List
DATA STRUCTURES USING C++ Chapter 5
Linked Lists Linear collections.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Section 5 Lists again. Double linked lists – insertion, deletion. Trees.
David Weinberg presents Linked Lists: The Background  Linked Lists are similar to ArrayLists in their appearance and method of manipulation  They do.
Review Learn about linked lists
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.
Data Structures: A Pseudocode Approach with C
Variations on Linked Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Linked list More terminology Singly-linked lists Doubly-linked lists DLLs compared to SLLs Circular Lists.
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.
1 Lecture 25 Abstract Data Types –II Overview  A stack Interface in Java  StackEmptyException  Stack ADT(A Simple Array-Based Implementation  Queue.
1 Lists. 2 Overview Arrays –Random access: –Fixed size: cannot grow on demand after creation:  Characteristics of some applications: –do not need random.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
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(
Lecture 6: Linked Lists Linked lists Insert Delete Lookup Doubly-linked lists.
Trees Weiss sec (preview) ch. 18 (sort of).
Chapter 3: Arrays, Linked Lists, and Recursion
Stacks, Queues, and Deques
Stacks, Queues, and Deques
Chapter 14 Queues. First a Review Queue processing Using queues to solve problems – Optimizing customer service simulation – Ceasar ciphers – Palindrome.
Doubly Linked Lists Deleting from the end of the list – Have to traverse the entire list to stop right in front of tail to delete it, so O(n) – With head.
Chapter 7 More Lists. Chapter 7: More Lists 7.1 – Circular Linked Lists 7.2 – Doubly Linked Lists 7.3 – Linked Lists with Headers and Trailers 7.4 – A.
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.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
LISTS Slides of K. Birman, Cornell University. List Overview 2  Purpose  Maintain an ordered collection of elements (with possible duplication)  Common.
Mohammad Amin Kuhail M.Sc. (York, UK) University of Palestine Faculty of Engineering and Urban planning Software Engineering Department Computer Science.
Section 4 Break Statement Usage Integer Class and other Wrapper class Inside Object Array Remove element from a list –Recursive approach –Iterative approach.
Linked Lists. 2 Anatomy of a linked list A linked list consists of: A sequence of nodes abcd  Each node contains a value  and a link (pointer or reference)
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
4-1 Topic 6 Linked Data Structures. 4-2 Objectives Describe linked structures Compare linked structures to array- based structures Explore the techniques.
Dynamic Array. An Array-Based Implementation - Summary Good things:  Fast, random access of elements  Very memory efficient, very little memory is required.
Week 4 - Monday.  What did we talk about last time?  Queues  Implementing queues with circular arrays.
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.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
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.
Copyright © 0 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
M180: Data Structures & Algorithms in Java Linked Lists Arab Open University 1.
1 Linked Lists (Lec 6). 2  Introduction  Singly Linked Lists  Circularly Linked Lists  Doubly Linked Lists  Multiply Linked Lists  Applications.
TREES K. Birman’s and G. Bebis’s Slides. Tree Overview 2  Tree: recursive data structure (similar to list)  Each cell may have zero or more successors.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
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.
CSCS-200 Data Structure and Algorithms Lecture
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
Queues CS 367 – Introduction to Data Structures. Queue A queue is a data structure that stores data in such a way that the last piece of data stored,
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
Linked Lists CS 367 – Introduction to Data Structures.
Data Structures and Algorithm Analysis Dr. Ken Cosh Linked Lists.
LINKED LISTS.
CS1020 L AB 3 (L INKED L IST ) Problem 1: Balls Problem 2: Josephine Problem 3: Keyboard.
Lecture 6 of Computer Science II
Lecture - 6 On Data Structures
LINKED LISTS CSCD Linked Lists.
Arrays and Linked Lists
List Data Structure.
Linked Lists.
Trees Lecture 9 CS2110 – Fall 2009.
CS2013 Lecture 4 John Hurley Cal State LA.
Presentation transcript:

LISTS & TREES Lecture 8 CS2110 – Fall 2008

List Overview 2  Purpose  Maintain an ordered set of elements (with possible duplication)  Common operations  Create a list  Access elements of a list sequentially  Insert elements into a list  Delete elements from a list  Arrays  Random access : )  Fixed size: cannot grow or shrink after creation : (  Linked Lists  No random access : (  Can grow and shrink dynamically : )

A Simple List Interface 3 public interface List { public void insert(T element); public void delete(T element); public boolean contains(T element); public int size(); }

List Data Structures  Array  Must specify array size at creation  Insert, delete require moving elements  Must copy array to a larger array when it gets full 4  Linked list  uses a sequence of linked cells  we will define a class ListCell from which we build lists empty

List Terminology  Head = first element of the list  Tail = rest of the list tailhead

Class ListCell 6  class ListCell {  private T datum;  private ListCell next;  public ListCell(T datum, ListCell next){  this.datum = datum;  this.next = next;  }  public T getDatum() { return datum; }  public ListCell getNext() { return next; }  public void setDatum(T obj) { datum = obj; }  public void setNext(ListCell c) { next = c; }  }

Building a Linked List  ListCell c  = new ListCell (new Integer(24), null); 7 24 –7 87 Integer t = new Integer(24); Integer s = new Integer(-7); Integer e = new Integer(87); ListCell p = new ListCell (t, new ListCell (s, new ListCell (e, null))); pListCell: c

Building a Linked List (cont’d) Integer t = new Integer(24); Integer s = new Integer(-7); Integer e = new Integer(87); //Can also use "autoboxing" ListCell p = new ListCell (e, null); p = new ListCell (s, p); p = new ListCell (t, p); pListCell: Another way: Note: p = new ListCell (s,p); does not create a circular list!

Accessing List Elements  Linked Lists are sequential-access data structures.  To access contents of cell n in sequence, you must access cells 0... n-1  Accessing data in first cell: p.getDatum()  Accessing data in second cell: p.getNext().getDatum()  Accessing next field in second cell: p.getNext().getNext() 9  Writing to fields in cells can be done the same way  Update data in first cell: p.setDatum(new Integer(53));  Update data in second cell: p.getNext().setDatum(new Integer(53));  Chop off third cell: p.getNext().setNext(null); pListCell:

Access Example: Linear Search 10  // Here is another version. Why does this work?  public static boolean search(Object x, ListCell c) {  for (; c != null; c = c.getNext()) {  if (c.getDatum().equals(x)) return true;  }  return false;  } Note: we’ ve left off the for simplicity // Scan list looking for x, return true if found public static boolean search(Object x, ListCell c) { for (ListCell lc = c; lc != null; lc = lc.getNext()) { if (lc.getDatum().equals(x)) return true; } return false; }

Recursion on Lists 11  Recursion can be done on lists  Similar to recursion on integers  Almost always  Base case: empty list  Recursive case: Assume you can solve problem on the tail, use that in the solution for the whole list  Many list operations can be implemented very simply by using this idea  Although some are easier to implement using iteration

Recursive Search 12  Base case: empty list  return false  Recursive case: non-empty list  if data in first cell equals object x, return true  else return the result of doing linear search on the tail

Recursive Search 13  public static boolean search(Object x, ListCell c) {  if (c == null) return false;  if (c.getDatum().equals(x)) return true;  return search(x, c.getNext());  } public static boolean search(Object x, ListCell c) { return c != null && (c.getDatum().equals(x) || search(x, c.getNext())); }

Reversing a List 14  Given a list, create a new list with elements in reverse order  Intuition: think of reversing a pile of coins  It may not be obvious how to write this recursively... public static ListCell reverse(ListCell c) { ListCell rev = null; for (; c != null; c = c.getNext()) { rev = new ListCell(c.getDatum(), rev); } return rev; }

Recursive Reverse 15 public static ListCell reverse(ListCell c) { return reverse(c, null); } private static ListCell reverse(ListCell c, ListCell r) { if (c == null) return r; return reverse(c.getNext(), new ListCell(c.getDatum(), r)); }

List with Header 16  Sometimes it is preferable to have a List class distinct from the ListCell class  The List object is like a head element that always exists even if list itself is empty  class List {  protected ListCell head;  public List(ListCell c) {  head = c;  }  public ListCell getHead()  ………  public void setHead(ListCell c)  ………  } Heap head List

Variations on List with Header 17  Header can also keep other info  Reference to last cell of list  Number of elements in list  Search/insertion/ deletion as instance methods  … Heap head List head tail head List tail size 3

Special Cases to Worry About 18  Empty list  add  find  delete  Front of list  insert  End of list  find  delete  Lists with just one element

Example: Delete from a List 19  Delete first occurrence of x from a list  Intuitive idea of recursive code:  If list is empty, return null  If datum at head is x, return tail  Otherwise, return list consisting of head of the list, and List that results from deleting x from the tail // recursive delete public static ListCell delete(Object x, ListCell c) { if (c == null) return null; if (c.getDatum().equals(x)) return c.getNext(); c.setNext(delete(x, c.getNext())); return c; }

Iterative Delete 20  Two steps:  Locate cell that is the predecessor of cell to be deleted (i.e., the cell containing x) Keep two cursors, scout and current scout is always one cell ahead of current Stop when scout finds cell containing x, or falls off end of list  If scout finds cell, update next field of current cell to splice out object x from list  Note: Need special case for x in first cell pList: 36 current scout current scout delete 36 from list : head: ListCell:

Iterative Code for Delete 21  public void delete (Object x) {  if (head == null) return;  if (head.getDatum().equals(x)) { //x in first cell?  head = head.getNext();  return;  }  ListCell current = head;  ListCell scout = head.getNext();  while ((scout != null) && !scout.getDatum().equals(x)) {  current = scout;  scout = scout.getNext();  }  if (scout != null) current.setNext(scout.getNext());  return;  }

Doubly-Linked Lists 22  In some applications, it is convenient to have a ListCell that has references to both its predecessor and its successor in the list next prev class DLLCell { private Object datum; private DLLCell next; private DLLCell prev; … }

Doubly-Linked vs Singly-Linked 23  Advantages of doubly-linked over singly-linked lists  some things are easier – e.g., reversing a doubly-linked list can be done simply by swapping the previous and next fields of each cell  don't need the scout to delete  Disadvantages  doubly-linked lists require twice as much space  insert and delete take more time

Java ArrayList 24  “Extensible array”  Starts with an initial capacity = size of underlying array  If you try to insert an element beyond the end of the array, it will allocate a new (larger) array, copy everything over invisibly  Appears infinitely extensible  Advantages:  random access in constant time  dynamically extensible  Disadvantages:  Allocation, copying overhead 24