Topic 12 The List ADT. 9-2 Objectives Examine list processing and various ordering techniques Define a list abstract data type Examine various list implementations.

Slides:



Advertisements
Similar presentations
Chapter 25 Lists, Stacks, Queues, and Priority Queues
Advertisements

TK1924 Program Design & Problem Solving Session 2011/2012
Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 17 Linked Data Structures. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Nodes and Linked Lists Creating,
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
Introduction to Computation and Problem
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
1 RA I Sub-Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Casablanca, Morocco, 20 – 22 December 2005 Status of observing programmes in RA I.
Lecture 15 Linked Lists part 2
Inserting a Node into a Specified Position of a Linked List To create a node for the new item newNode = new Node(item); To insert a node between two nodes.
Chapter 17 Linked Lists.
COMP171 Fall 2005 Lists.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Singly Linked Lists What is a singly-linked list? Why linked lists?
Building Java Programs Chapter 10
Lists Chapter 6 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Linked List A linked list consists of a number of links, each of which has a reference to the next link. Adding and removing elements in the middle of.
DATA STRUCTURES AND ALGORITHMS Prepared by İnanç TAHRALI
Linked Lists Chapter 4.
List Implementations That Use Arrays
Queues and Linked Lists
1111 Abstract Data Types Cpt S 223. School of EECS, WSU.
Data Structures: A Pseudocode Approach with C
Data Structures ADT List
Chapter 24 Lists, Stacks, and Queues
Linked Lists Linear collections.
11 Data Structures Foundations of Computer Science ã Cengage Learning.
ITEC200 Week04 Lists and the Collection Interface.
1 CSE1301 Computer Programming: Lecture 27 List Manipulation.
Data Structures Using C++
Chapter 11 Array-Based Lists.
COSC 1P03 Data Structures and Abstraction 10.1 The List If A is success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping.
Data Structures Part 2 Stacks, Queues, Trees, and Graphs Briana B. Morrison CSE 1302C Spring 2010.
Double-Linked Lists and Circular Lists
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
Chapter 15 Lists. Chapter Scope Types of list collections Using lists to solve problems Various list implementations Comparing list implementations Java.
1 DATA STRUCTURES. 2 LINKED LIST 3 PROS Dynamic in nature, so grow and shrink in size during execution Efficient memory utilization Insertion can be.
CSE Lecture 12 – Linked Lists …
1 Lists A List ADT Types of Lists Lists in Java Collections API Using ordered lists – Tournament Maker Using indexed lists – Josephus Problem Implementing.
The List ADT Textbook Sections
1 RA III - Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Buenos Aires, Argentina, 25 – 27 October 2006 Status of observing programmes in RA.
Basel-ICU-Journal Challenge18/20/ Basel-ICU-Journal Challenge8/20/2014.
1..
CONTROL VISION Set-up. Step 1 Step 2 Step 3 Step 5 Step 4.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
Lecture Queues. The name ‘Queue’ derives from objects that have to queue in order to be dealt with A queue is a First-In-First-Out(FIFO) or a Last-In-Last-Out(LILO)
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 11: Priority Queues and Heaps Java Software Structures: Designing.
Essential Cell Biology
PSSA Preparation.
Essential Cell Biology
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Pointers and Linked Lists.
Topic 16 Sorting Using ADTs to Implement Sorting Algorithms.
Energy Generation in Mitochondria and Chlorplasts
Chapter 14 Introduction to Collections
1 Lists A List ADT Types of Lists Lists in Java Collections API Using ordered lists – Tournament Maker Using indexed lists – Josephus Problem Implementing.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
CHAPTER 8 Lists. 2 A list is a linear collection Adding and removing elements in lists are not restricted by the collection structure We will examine.
Chapter 8 Lists. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-2 Chapter Objectives Examine list processing and various ordering techniques.
Topic 3 The Stack ADT.
Lists Based on content from: Java Foundations, 3rd Edition.
Chapter 8 Lists. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine list processing and various ordering techniques.
4-1 Topic 6 Linked Data Structures. 4-2 Objectives Describe linked structures Compare linked structures to array- based structures Explore the techniques.
Chapter 2 Collections. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Define the concept and terminology related.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
The List ADT.
Top Ten Words that Almost Rhyme with “Peas”
Java Software Structures: John Lewis & Joseph Chase
Presentation transcript:

Topic 12 The List ADT

9-2 Objectives Examine list processing and various ordering techniques Define a list abstract data type Examine various list implementations Compare list implementations

9-3 Lists A list is a linear collection, like a stack and queue, but more flexible: adding and removing elements from a list does not have to happen at one end or the other We will examine three types of list collections: ordered lists unordered lists indexed lists

9-4 Ordered Lists Ordered list: Its elements are ordered by some inherent characteristic of the elements Examples: Names in alphabetical order Numeric scores in ascending order So, the elements themselves determine where they are stored in the list

9-5 Conceptual View of an Ordered List frontrear New values must be inserted so that the ordering of the list is maintained

9-6 Unordered Lists Unordered list : the order of the elements in the list is not based on a characteristic of the elements, but is determined by the user of the list A new element can be put on the front of the list or on the rear of the list or after a particular element already in the list Examples : shopping list, to-do list, …

9-7 Conceptual View of an Unordered List frontrear New values can be inserted anywhere in the list

9-8 Indexed Lists Indexed list: elements are referenced by their numeric position in the list, called its index Its the position in the list that is important, and the user can determine the order that the items go in the list Every time the list changes, the position (index) of an element may change Example: current first-place holder in the bobsled race

9-9 Conceptual View of an Indexed List frontrear New values can be inserted at any position in the list

9-10 List Operations Operations common to all list types include : Removing elements in various ways Checking the status of the list (isEmpty, size) Iterating through the elements in the list (more on this later!) The key differences between the list types involve the way elements are added: To an ordered list? To an unordered list? To an indexed list?

9-11 The Common Operations on a List OperationDescription removeFirstRemoves the first element from the list removeLastRemoves the last element from the list removeRemoves a particular element from the list firstExamines the element at the front of the list lastExamines the element at the rear of the list containsDetermines if a particular element is in the list isEmptyDetermines whether the list is empty sizeDetermines the number of elements in the list iteratorReturns an iterator for the lists elements toStringReturns a string representation of the list

9-12 Operation Particular to an Ordered List OperationDescription addAdds an element to the list (in the correct place)

9-13 Operations Particular to an Unordered List OperationDescription addToFrontAdds an element to the front of the list addToRearAdds an element to the rear of the list addAfterAdds an element after a particular element already in the list

9-14 Operations Particular to an Indexed List OperationDescription addAdds an element at a particular index in the list setSets the element at a particular index in the list getReturns a reference to the element at the specified index indexOfReturns the index of the specified element removeRemoves and returns the element at a particular index

9-15 List Operations We use Java interfaces to formally define the operations on the lists, as usual Note that interfaces can be defined via inheritance (derived from other interfaces) Define the common list operations in one interface See ListADT.java Derive the thee others from it see OrderedListADT.java see UnorderedListADT.java see IndexedListADT.java

9-16 ListADT Interface import java.util.Iterator; public interface ListADT { // Removes and returns the first element from this list public T removeFirst ( ); // Removes and returns the last element from this list public T removeLast ( ); // Removes and returns the specified element from this list public T remove (T element); // Returns a reference to the first element on this list public T first ( ); // Returns a reference to the last element on this list public T last ( ); // contd..

9-17 //..contd // Returns true if this list contains the specified target element public boolean contains (T target); // Returns true if this list contains no elements public boolean isEmpty( ); // Returns the number of elements in this list public int size( ); // Returns an iterator for the elements in this list public Iterator iterator( ); // Returns a string representation of this list public String toString( ); }

9-18 OrderedList ADT public interface OrderedListADT extends ListADT { // Adds the specified element to this list at the proper location public void add (T element); }

9-19 UnorderedListADT public interface UnorderedListADT extends ListADT { // Adds the specified element to the front of this list public void addToFront (T element); // Adds the specified element to the rear of this list public void addToRear (T element); // Adds the specified element after the specified target public void addAfter (T element, T target); }

9-20 IndexedListADT public interface IndexedListADT extends ListADT { // Inserts the specified element at the specified index public void add (int index, T element); // Sets the element at the specified index public void set (int index, T element); // Adds the specified element to the rear of this list public void add (T element); // Returns a reference to the element at the specified index public T get (int index); // Returns the index of the specified element public int indexOf (T element); // Removes and returns the element at the specified index public T remove (int index); }

9-21 Discussion Note that the add method in the IndexedList ADT is overloaded So is the remove method Why? Because there is a remove method in the parent ListADT This is not overriding, because the parameters are different

9-22 > ListADT removeFirst( ) removeLast( ) remove(T) first( ) last( ) contains(T) isEmpty( ) size( ) iterator( ) toString( ) > OrderedListADT add(Comparable) > UnorderedListADT addToFront(T) addToRear(T) addAfter(element:T, target:T) > IndexedListADT add(T) add(int, T) set(int, T) get(int) indexOf(T) remove(int) UML Diagrams for Various List Interfaces

9-23 List Implementation using Arrays Container is an array Fix one end of the list at index 0 and shift as needed when an element is added or removed Is a shift needed when an element is added at the front? somewhere in the middle? at the end? Is a shift needed when an element is removed from the front? from somewhere in the middle? from the end?

9-24 An Array Implementation of a List rear 4 list ? 5 ? … An array-based list ls with 4 elements ? ls

9-25 UML Diagram for ArrayList > ListADT removeFirst( ) removeLast( ) remove(T element) first( ) last( ) contains() isEmpty( ) size( ) iterator( ) toString( ) ArrayList rear list NOT_FOUND DEFAULT_CAPACITY removeFirst( ) removeLast( ) remove(T element) first( ) last( ) contains() isEmpty( ) size( ) iterator( ) toString( ) - find( ) - expandCapacity( ) Class ArrayList will be extended to yield classes ArrayOrderedList, ArrayUnorderedList, etc.

9-26 // // Removes and returns the specified element. // public T remove (T element) throws ElementNotFoundException { T result; int index = find (element); // uses helper method find if (index == NOT_FOUND) throw new ElementNotFoundException("list"); result = list[index]; rear--; // shift the appropriate elements for (int scan=index; scan < rear; scan++) list[scan] = list[scan+1]; list[rear] = null; return result; } The remove( ) operation

9-27 // // Returns the array index of the specified element, // or the constant NOT_FOUND if it is not found. // private int find (T target) { int scan = 0, result = NOT_FOUND; boolean found = false; if (! isEmpty( )) while (! found && scan < rear) if (target.equals(list[scan]) found = true; else scan++; if (found) result = scan; return result; } The find( ) helper method

9-28 // // Returns true if this list contains the specified element. // public boolean contains (T target) { return (find(target) != NOT_FOUND); //uses helper method find } The contains( ) operation

9-29 // // Adds the specified Comparable element to the list, // keeping the elements in sorted order. // public void add (T element) { if (size( ) == list.length) expandCapacity( ); Comparable temp = (Comparable )element; int scan = 0; while (scan 0) scan++; for (int scan2=rear; scan2 > scan; scan2--) list[scan2] = list[scan2-1] list[scan] = element; rear++; } The add( ) operation of ArrayOrderedList

9-30 The Comparable Interface For an ordered list, the actual class for the generic type T must have a way of comparing elements so that they can be ordered So, it must implement the Comparable interface, i.e. it must define a method called compareTo But, the compiler does not know whether or not the class that we use to fill in the generic type T will have a compareTo method

9-31 The Comparable Interface So, to make the compiler happy: Declare a variable that is of type Comparable Convert the variable of type T to the variable of type Comparable Comparable temp = (Comparable )element; Note that an object of a class that implements Comparable can be referenced by a variable of type Comparable

9-32 List Implementation Using Arrays, Method 2: Circular Arrays Recall circular array implementation of queues Exercise: implement list operations using a circular array implementation

9-33 List Implementation Using Links We can implement a list collection with a linked list as the container Implementation uses techniques similar to ones we've used for stacks and queues We will first examine the remove operation for a singly-linked list implementation Then well look at the remove operation for a a doubly-linked list, for comparison

9-34 // // Removes the first instance of the specified element // from the list, if it is found in the list, and returns a // reference to it. Throws an ElementNotFoundException // if the specified element is not found on the list. // public T remove (T targetElement) throws ElementNotFoundException { if (isEmpty( )) throw new ElementNotFoundException ("List"); boolean found = false; LinearNode previous = null LinearNode current = head; // contd.. The remove( ) operation (singly-linked list)

9-35 while (current != null && !found) if (targetElement.equals (current.getElement( ))) found = true; else { previous = current; current = current.getNext( ); } if (!found) throw new ElementNotFoundException ("List"); if (size( ) == 1) head = tail = null; else if (current.equals (head)) head = current.getNext( ); else // contd The remove( ) operation (contd)

9-36 if (current.equals (tail)) { tail = previous; tail.setNext(null); } else previous.setNext(current.getNext( )); count--; return current.getElement( ); } The remove( ) operation (contd)

9-37 Doubly Linked Lists A doubly linked list has two references in each node: One to the next element in the list One to the previous element This makes moving back and forth in a list easier, and eliminates the need for a previous reference in particular algorithms Disadvantage? a bit more overhead when managing the list

9-38 Implementation of a Doubly- Linked List count 4 rear front.. A doubly-linked list dl with 4 elements dl

9-39 See DoubleNode.java We can then implement the ListADT using a doubly linked list as the container Following our usual convention, this would be called DoublyLinkedList.java

9-40 // // Removes and returns the specified element. // public T remove (T element) throws ElementNotFoundException { T result; DoubleNode nodeptr = find (element); // uses helper method find for doubly-linked list if (nodeptr == null) throw new ElementNotFoundException ("list"); result = nodeptr.getElement( ); // check to see if front or rear if (nodeptr == front) result = this.removeFirst( ); // contd.. The remove( ) operation (doubly-linked list)

9-41 else if (nodeptr == rear) result = this.removeLast( ); else { nodeptr.getNext( ).setPrevious(nodeptr.getPrevious( )); nodeptr.getPrevious( ).setNext(nodeptr.getNext( )); count--; } return result; } The remove( ) operation (contd)

9-42 Analysis of List Implementations In both array and linked implementations, many operations are similar in efficiency Most are O(1), except when shifting or searching need to occur, in which case they are order O(n) Exercise: determine the time complexity of each operation In particular situations, the frequency of the need for particular operations may guide the use of one approach over another