Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 1 Principles for implementing ADTs ADT operations as “walls” between.

Slides:



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

Singly linked lists Doubly linked lists
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.
Stacks, Queues, and Linked Lists
Linked Lists Chapter 4.
Data Structures ADT List
David Weinberg presents Linked Lists: The Background  Linked Lists are similar to ArrayLists in their appearance and method of manipulation  They do.
M180: Data Structures & Algorithms in Java
1 Queues (5.2) CSE 2011 Winter May Announcements York Programming Contest Link also available from.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
CS Data Structures II Review COSC 2006 April 14, 2017
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
© 2006 Pearson Addison-Wesley. All rights reserved5 A-1 Chapter 5 Linked Lists CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
© 2006 Pearson Addison-Wesley. All rights reserved11 B-1 Chapter 11 (continued) Trees.
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.
Linked Lists. Preliminaries Options for implementing an ADT List Array Has a fixed size Data must be shifted during insertions and deletions Dynamic array.
List Implementations That Use Arrays Chapter 5. 2 Chapter Contents Using a Fixed-Size Array to Implement the ADT List An Analogy The Java Implementation.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
© 2006 Pearson Addison-Wesley. All rights reserved5 A-1 Chapter 5 Linked Lists.
Data Structures Topic #3. Today’s Agenda Ordered List ADTs –What are they –Discuss two different interpretations of an “ordered list” –Are manipulated.
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.
Marc Smith and Jim Ten Eyck
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.
Chapter 7 Stacks II CS Data Structures I COSC 2006
SAK 3117 Data Structures Chapter 6: LINKED LISTS.
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
ليست هاي پيوندي Linked Lists ساختمان داده ها و الگوريتم ها.
Lists II. List ADT When using an array-based implementation of the List ADT we encounter two problems; 1. Overflow 2. Wasted Space These limitations are.
April 24, 2017 Chapter 4 Data Abstraction The Walls
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.
CS 307 Fundamentals of Computer ScienceLinked Lists 1 Topic 14 Linked Lists "All the kids who did great in high school writing pong games in BASIC for.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Chapter 5 Linked Lists II
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
CS2006- Data Structures I Chapter 5 Linked Lists III.
Copyright © 0 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
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.
M180: Data Structures & Algorithms in Java Linked Lists Arab Open University 1.
CS 367 Introduction to Data Structures Lecture 5.
List Interface and Linked List Mrs. Furman March 25, 2010.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 18 List ADT Animated Version.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
CSCS-200 Data Structure and Algorithms Lecture
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
LINKED LISTS.
Data Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
An Array-Based Implementation of the ADT List
Linked Data Structures
Linked Lists Chapter 5 (continued)
Stacks.
Data Abstraction A technique for increasing the modularity of a program The need to support several operations on the data arise need to define abstract.
Ch. 4 Data Abstraction Modular programming Procedural abstraction
Programming II (CS300) Chapter 07: Linked Lists and Iterators
CS2013 Lecture 4 John Hurley Cal State LA.
Ch. 5 Linked List When a list is implemented by an array Linked list
Linked Lists The items in a linked list data structure are linked to one another An item in a linked list references its successor A linked list is able.
Linked Lists Chapter 5 (continued)
Programming II (CS300) Chapter 07: Linked Lists
8 List ADTs List concepts. List applications.
TCSS 143, Autumn 2004 Lecture Notes
Linked Lists Chapter 5 (continued)
Presentation transcript:

Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 1 Principles for implementing ADTs ADT operations as “walls” between programs and data structures ADT operations are declared using an interface in Java. Data structure is defined using a class that implements the interface Variables for storing ADT items are private data field of this class ADT operations are implemented as public methods of this class Auxiliary methods are private methods of this class.

Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 2 List Interface for the ADT List public interface List { public boolean isEmpty(); //Pre: none //Post: Returns true if the list is empty, otherwise returns false. public int size(); //Pre:none //Post: Returns the number of items currently in the list. public T get(int givenPos) throws ListIndexOutOfBoundsException //Pre: givenPos is the position in the list of the element to be retrieved //Post: If 1<= givenPos <= size(), the item at givenPos is returned. //Throws: ListIndexOutOfBoundsException if givenPos = size()+1 Continued ….

Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 3 public void add(int givenPos, T newItem) throws ListIndexOutOfBoundsException, ListException ; //Pre: givenPos indicates the position at which newItem should be inserted //Post: If 1<= givenPos <= size() + 1, newItem is at givenPos, and elements // at givenPos and onwards are shifted one position to the right. //Throws: ListIndexOutOfBoundsException when givenPos size()+1 //Throws: ListException if newItem cannot be placed in the list. public void remove(int givenPos) throws ListIndexOutOfBoundsException ; //Pre: givenPos indicates the position in the list of the element to be removed //Post: If 1<= givenPos <= size(), the element at position givenPos is deleted, and // items at position greater than givenPos are shifted one position to the left. //Throws: ListIndexOutOfBoundsException if givenPos size(). } //end of List …. ListInterface for the ADT List

Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 4 Exceptions A list operation provided with givenPosition out of range (out-of-bound exception): public class ListIndexOutofBoundsException extends IndexOutofBoundsException{ public ListIndexOutofBoundsException(String s){ super(s); } //end constructor } //end ListIndexOutofBoundsException Array storing the list becomes full (a list exception) public class ListException extends RuntimeException{ public ListException(String s){ super(s); } //end constructor } //end ListException

Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 5 Static Implementation of ADT List A static implementation : uses an array of a specific maximum length, and all storage is allocated before run-time. orders the elements in the array with the array index related to the position of the element in the list. We need: a variable to keep track of the current number of elements in the list, or current size of the list. a variable to record the maximum length of the array, and therefore of the list Data Structure: private final int maxList = 100; //max length of the list private T elems[maxList]; //array of elements in the list private int numElems; //current size of the list

Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 6 Delete item at position 4 from the list - remove(4) k numElems elems 12390………..510 ?……..? k maxList -1 k1234 maxList … List of k elements Add 44 at position 3 in the list - add(3, 44) 0123 maxList -1 k maxList 4 k+1 numElems ………..510…….. k 44 elems ………..510…….. elems k numElems 0123k k maxList -1 maxList Data structure and operations Array index List position

Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 7 Array-based Implementation of List public class ArrayBasedList implements List { private static final int maxList = 50; private T[] elems; // a list of elements private int numElems; // current number of elements in the list public ArrayBasedList(){ elems= (T[]) new Object[maxList]; numElems = 0; } public boolean isEmpty(){ return (numElems == 0);} public int size(){ return numElems;} public T get(int givenPos) throws ListIndexOutOfBoundsException{ if (givenPos >= 1 && givenPos <= numElems) { return elems[translate(givenPos)]; } else {throw new ListIndexOutOfBoundsException(“Position out of range”);} }// end get Continued ….

Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 8 Array-based Implementation of List public void add(int givenPos, T newItem) throws ListIndexOutOfBoundsException, ListException { if (numElems == maxList) { throw new ListException(“List is full”); } if (givenPos >=1 && givenPos <= numElems + 1){ makeRoom(givenPos); elems[translate(givenPos)]= newItem; //insert newItem numElems++; } else throw new ListIndexOutOfBoundsException(“Position out of range”); }// end add Continued …. private int translate(int position){ return position –1; }//end translate private void makeRoom(int position) { //pre: 1 <= position <= numElems + 1 for (int pos=numElems; pos>=position; pos--) { elems[translate(pos+1)] = elems[translate(pos)]; } }

Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 9 Array-based Implementation of List public void remove(int givenPos) throws ListIndexOutOfBoundsException{ if (givenPos >=1 && givenPos <= numElems){ if (givenPos < numElems){ // delete item by shifting left all item at position > givenPos removeGap(givenPos); } numElems--; } else throw new ListIndexOutOfBoundsException(“Position out of range”); }// end remove private void removeGap(int position){ //pre: 1=< position < numElems for (int pos=position+1; pos<=size(); pos++){ elems[translate(pos-1)] = elems[translate(pos)];} } }//end ListArrayBased

Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 10 Example: simple text editor References text.numElems, text.elems[4], text.translate(6) are ILLEGAL. public class TextEditor { private List text; private int sel; public TextEditor () { text = new ArrayBasedList (); sel = 0;} ……………

Course: Object Oriented Programming - Abstract Data Types Slide Number 11 Alternative static-implementation Making use of dynamic expansion of an array Current array Expanded array  Requires copying all existing elements of a list from the current array data structures to a new larger array  Larger array has to be at least the double of the original one  Extra computational cost but controllable memory waste. Unit2: ADT Lists

Course: Object Oriented Programming - Abstract Data Types Unit2: ADT ListsSlide Number 12 Java provides an interface List similar to the one defined in this lecture. It is part of java.util.List public interface List extends Collection Java provides various implement the list interface, each using specific data structures. Lists as part of Java Collection java.util.ArrayList represents each list by an array. java.util.LinkedList represents each list by a doubly-linked list. The above implementations are not synchronized. It requires external mechanisms for synchronizing access by multiple threads to the same list.

Course: Object Oriented Programming - Abstract Data Types Slide Number 13 Dynamic Implementation of Lists Linked list: Nodes connected to one another by links, plus a header (i.e. the beginning of the list) head elemnext elemnextelemnext Null elemnextelemnextelemnext The dynamic implementation of lists uses linked list structures Data Structure:  a reference variable of type node head  a node data type element link Unit2: ADT Linked Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 14 class Node { private T element; private Node next; ………… } class LinkedBasedList { private Node head; private int numElems; ………… } Implementation of List methods Data Structure of a Linked List Unit2: ADT Linked Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 15 Implementing the class Node public class Node { private T element; private Node next; public void setElem(T newElem){ element = newElem; } public T getElem( ){ return element; } public void setNext(Node newNode){ next = newNode; } public Node getNext( ){ return next; } private class Node{ private T element; private Node next; private Node(T newElem){ element = newElem; next = null; } private Node(T newElem, Node newNode){ element = newElem; next = newNode; } } Package level classInner class Unit2: ADT Linked Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 16 Implementing LinkedBasedList(1) public class LinkedBasedList implements List { private Node head; private int numElems; public LinkedBasedList(){ head = null; numElems = 0; } > private Node getNodeAt(int givenPos) private class Node{ > } } Unit2: ADT Linked Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 17  The next attribute of the last node object in a list should be set to null.  When the list is empty, the reference variable head should have value null.  When last reference to a node is removed, the system marks the node for garbage collection. Main invariants Creating and Linking two nodes head = new Node(new Integer(5)); head 5 Implementing LinkedBasedList(2) head = null; head 5 garbage Node n1 = new Node( ); Node n2 = new Node( ); n1 n2 n1.setElem(new Integer(5)); n2.setElem(new Integer(9)); 5 9 n1.setNext(n2); Unit2: ADT Linked Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 18 Deleting a Node in a Linked List Three main steps: 1.Locate the node to delete. 2.Disconnect this node from the linked list by changing references. 3.Return the node to the system. E.g.: delete the second Node in the list head 20 Null prev curr Null prev curr Unit2: ADT Linked Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 19 Three main steps: 1.Determine the point of insertion 2.Create a new node and store the new data in it. 3.Connect the new node to the linked list by changing references. prev Adding a Node in a Linked List E.g.: insert a new Node at position 3: head 20 Null newNode Unit2: ADT Linked Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 20 The interface List is the same as for ArrayBasedList public class LinkedBasedList implements List { private Node head; private int numElems; } The class LinkedBasedList implements List : Reference variables “prev” and “curr” are local to the methods that need them; they are not data fields of the class LinkedBasedList. A method “ getNodeAt(i) ” is an auxiliary method that takes a position i and returns a reference to the i th node in the linked list. Implementing LinkedBasedList (2) Unit2: ADT Linked Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 21 The interface List is the same as for ListArrayBased public class LinkedBasedList implements List { private Node head; private int numElems; } The class LinkedBasedList implements List : Reference variables “prev” and “curr” are local to the methods that need them; they are not data fields of the class LinkedBasedList. A method “ getNodeAt(i) ” is an auxiliary method that takes a position i and returns a reference to the i th node in the linked list. Implementing LinkedBasedList (2) Unit2: ADT Linked Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 22 …..Example Implementations of some Methods public LinkedBasedList( ){ numElems = 0; head = null; } public boolean isEmpty( ){ return numElems == 0; } private Node getNodeAt(int givenPos){ // pre: givenPos is the position of the desired node, // pre: assume 1  givenPos  numElems; // post: returns reference to the node at a givenPos; Node curr = head; for (int skip = 1; skip < givenPos; skip++){ curr = curr.getNext(); } return curr; } Unit2: ADT Linked Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 23 Example use of a Linked List public class Entry { private String element; private int amount; public Entry(String elementData, int amountData){ element = elementData; amount = amountData; } public String toString( ){ return (element + “ “ + amount); } public class GenericLinkedListDemo { public static void main(String[] args){ List list = new LinkedBasedList ( ); Entry e1 = new Entry(“apple”, 5); Entry e2 = new Entry(“banana”, 5); Entry e3 = new Entr(“cantaloupe”,1); list.add(1, e1); list.add(1, e2); list.add(1, e3); System.out.println(“ List has ” + list.size() + “ elements. ”); list.diplay(); System.out.println(“End of list. ”); } } List has 3 elements. cantaloupe 1 banana 3 apples 5 End of list. Sample dialogue: cantaloupe, 1banana, 3apple, 5 Unit2: ADT Linked Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 24 List Variations Doubly – Linked Lists Node has 2 reference variables for previous node and next node Reference variable to the previous node in the first node is null; similarly for the reference variable to the next node in the last node. public class Node { private T item; private Node next; private Node previous; } Node head 20 elemnextprev tail Unit2: ADT Linked Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 25 List Variations (continued) A single-linked list in which the last node references the head of the list. It allows the search for sequences of elements to continue from a “current position”, rather than always starting at the head of the list. Circular Lists entry Point Unit2: ADT Linked Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 26 Ordered Linked List An ordered linked list is a linked list where elements have a special attribute, called key, and are totally ordered with respect to their key. createOrderedList( ) // post: Create an empty ordered list put(searchKey, givenValue) //post: Insert in the list an element with searchKey //and givenValue in the correct position. //If a node with searchKey exists, set its //value to be equal to givenValue. isEmpty( ) // post: Determine if an ordered list is //empty size( ) // post: Returns the number of elements in // an ordered list remove(searchKey) //post: Removes the element whose key is equal //to searchKey. Throws exception if such an //element does not exist. get(searchKey) //post: Returns the element with key equal //to searchKey. Returns null if the searchKey //is not in the list Access procedures: Unit2: ADT Ordered Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 27 Data Structure of an Ordered Linked List class Node { private K key; private V value; private Node next; ……… } class OrderedList,V>{ private Node head; private int numElems; ……… } Unit2: ADT Ordered Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 28 Getting an element from an Ordered Linked List Algorithm get(K searchKey){ // post: search the Node whose key is equal to searchKey // and returns its value. Let prev be equal to head; if (prev is null) { the desired Node is not found, return null; } else if (prev.key is equal to searchKey) { the desired Node is found, return its value; } else {curr is equal to the next node; while (curr is different from null && curr.key is less then searchKey){ pre is equal to curr; curr is equal to the next node; } if (curr is different from null and curr.key is equal to searchKey){ return curr.value;} } return null; } You can use here a method compareTo(searchKey) You can use here a method equals(searchKey) Unit2: ADT Ordered Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 29 Inserting an item in an Ordered Linked List Algorithm put(K searchKey, V givenValue){ // post: add a new Node with searchKey and givenValue, to the ordered linked list // so that the order is satisfied. If a Node with givenKey already exists, its value is // replaced with givenValue. > if (prev is null) { Add node at the head of the list; } else if (prev.key is equal to searchKey) { set prev.value to be the givenValue; } else if (prev.key is less then searchKey) { add a new node with givenKey and givenValue after prev;} else {add a new node with givenKey and givenValue as first node;} } Unit2: ADT Ordered Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 30 Method “findPrev” for Ordered Linked Lists private Node findPrev(K searchKey){ // post: Returns the Node with key equal to searchKey, if any exists in the list. Or // it returns the previous key (if any). Or if the previous key does not exists, it // returns the Node with key after searchKey (if any). Or it returns null if the list is // empty Node prev = head; if ((prev != null)&&(prev.getKey().comparedTo(searchKey) curr = prev.getNext(); while ((curr != null)&&(curr.getKey().comparedTo (searchKey) <= 0){ prev = curr; curr = curr.getNext( ); } } return prev; } Unit2: ADT Ordered Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 31 List Iterator An iterator is a program component that steps through, or traverses a collection of data. public interface List extends Iterable { iterator()> } public class LinkedBasedList implements List { ////// Iterator /////////// public Iterator iterator(){ return new ListIterator (); } ///// Inner class ///////// private class ListIterator implements Iterator { ………… } ………… } private class ListIterator implements Iterator { private Node current; private ListIterator (){ current = head; } public boolean hasNext() { return current != null; } public T next() { if (current == null){ return null; } else{result = current.getElem(); current = current.getNext(); return result; } } } Unit2: ADT Ordered Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 32 public void display(){ for(int pos=1; pos<=mylist.size(); pos++){ System.out.println(mylist.get(pos)); } } A list iterator would allow a more efficient traversal public void display(){ Iterator iterator = mylist.iterator(); T tmp; while(iterator.hasNext()){ tmp = iterator.next(); System.out.println(tmp); } Using a List Iterator Unit2: ADT Ordered Lists

Course: Object Oriented Programming - Abstract Data Types Slide Number 33 Summary Lists may be implemented statically or dynamically: OperationsFixed-size ArrayLinked List add(pos, elem)O(n) to O(1)O(1) to O(n) remove(pos)O(n) to O(1)O(1) to O(n) get(pos)O(1)O(1) to O(n) display()O(n) size(), isEmpty()O(1) How do they compare? Time efficiency expressed in Big Oh notation Unit2: ADT Ordered Lists