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)

Slides:



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

Chapter 22 Implementing lists: linked implementations.
Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Why not just use Arrays? Java ArrayLists.
Introduction to Computation and Problem
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
1 Linked Lists Continued Lecture 5 Copying and sorting singly linked lists Lists with head and last nodes Doubly linked lists ADS2 Lecture 5.
Singly linked lists Doubly linked lists
Stacks, Queues, and Linked Lists
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.
Linked Lists Chapter 4.
Data Structures ADT List
DATA STRUCTURES USING C++ Chapter 5
Chapter 24 Lists, Stacks, and Queues
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.
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
Double-Linked Lists and Circular Lists
John Hurley Cal State LA
CSE Lecture 12 – Linked Lists …
The List ADT Textbook Sections
1 Array-based Implementation An array Q of maximum size N Need to keep track the front and rear of the queue: f: index of the front object r: index immediately.
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.
David Weinberg presents Linked Lists: The Background  Linked Lists are similar to ArrayLists in their appearance and method of manipulation  They do.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
COSC 1P03 Data Structures and Abstraction 9.1 The Queue Whenever you are asked if you can do a job, tell 'em, "Certainly, I can!" Then get busy and find.
0 of 37 Stacks and Queues Lecture of 37 Abstract Data Types To use a method, need to know its essentials: signature and return type o additionally,
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.
Queues 4/14/2017 5:24 PM 5.2 Queues Queues Dr Zeinab Eid.
Chapter 6 Linked Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Data Structures Topic #3. Today’s Agenda Ordered List ADTs –What are they –Discuss two different interpretations of an “ordered list” –Are manipulated.
Lecture 6: Linked Lists Linked lists Insert Delete Lookup Doubly-linked lists.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 26 Implementing Lists, Stacks,
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
AITI Lecture 20 Trees, Binary Search Trees Adapted from MIT Course 1.00 Spring 2003 Lecture 28 and Tutorial Note 10 (Teachers: Please do not erase the.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
LinkedList Many slides from Horstmann modified by Dr V.
COP INTERMEDIATE JAVA Data Structures. A data structure is a way of organizing a collection of data so that it can be manipulated effectively. A.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
2014-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
CSC 212 – Data Structures Lecture 17: Stacks. Question of the Day Move one matchstick to produce a square.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Week 4 - Monday.  What did we talk about last time?  Queues  Implementing queues with circular arrays.
Linked List by Chapter 5 Linked List by
AITI Lecture 18 Introduction to Data Structure, Stack, and Queue Adapted from MIT Course 1.00 Spring 2003 Lecture 23 and Tutorial Note 8 (Teachers: Please.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
Chapter 15 Linked Data Structures Slides prepared by Rose Williams, Binghamton University Kenrick Mock University of Alaska Anchorage Copyright © 2008.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
List Interface and Linked List Mrs. Furman March 25, 2010.
Queue. Avoid confusion Britain Italy 6 Applications of Queues Direct applications –Waiting lists, bureaucracy –Access to shared resources (e.g.,
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
Java linked list.
1 Chapter 4 Unordered List. 2 Learning Objectives ● Describe the properties of an unordered list. ● Study sequential search and analyze its worst- case.
Click to edit Master text styles Stacks Data Structure.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
CSCI 62 Data Structures Dr. Joshua Stough September 23, 2008.
Linked Data Structures
Queues 5/11/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H.
Double-Ended Queues Chapter 5.
Marcus Biel, Software Craftsman
Queue.
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
Stacks, Queues, and Deques
Presentation transcript:

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)

The Java Collection Classes The java.util package contains implementations of many data structures that we are also going to discuss and implement in a simpler way in class. You are welcome to use the standard Java implementations in problem sets. They are more elaborate and abstract than the implementations we will develop. Learning how to implement a few data structures makes you more sophisticated in how you use all data structures.

Lists as an Abstract Data Type A list is a collection of elements that has a particular order. –It can have arbitrary length. –You should be able to insert or delete an element anywhere. –You should be able to go through the list in order an element at a time.

A List Interface public interface List { public boolean isEmpty(); public void addFirst( Object o ); public void addLast( Object o ); public boolean contains(Object o); public boolean removeLast() // Error in notes throws NoSuchElementException; public Object removeFirst() throws NoSuchElementException; public void clear(); public int size(); public void print(); }

List Implementation Stategies There are many ways to implement a list. In array-based implementations like the Java Vector inserting an element at any place except the end of the list is very expensive because all the elements from the point of insertion until the end must be moved back to make room for the new entry. There is a similar problem with deletion. For this reason, lists frequently use a linked implementation.

Singly Linked Lists Linked lists are like freight trains. Each item to be put on the list is contained in an instance of a new type of object called the link corresponding to a freight car. In a singly linked list, the link not only contains the listed item, but it also points to the next item in the list as one freight car is coupled to the next. The last link in the list points to nothing.

Singly Linked List Diagram List firstlast Link 1 Item 1 Link n Item 2 Item n... null Link 2

Singly Linked Lists, 2 The list object itself points to the link holding the first listed item, and often holds an additional reference to the last link of the list to make it easier to append items. We say that a link contains or points to, and the list instance points or holds a pointer. In Java these are all synonyms for holding a reference. So the link doesn't really contain the item. It simply holds a reference to the listed item. The last link holds a null reference in the field that points to the next element.

The Link Inner Class public class SLinkedList implements List { private static class SLink { Object item; SLink next; SLink( Object o, SLink n ) { item = o; next = n; } SLink( Object o ) { this( o, null ); } }...

Generic vs. Typed Lists The List interface we have specified is general like the Java Vector class. It stores and retrieves Objects. If you are writing your own list class, and you know you will only be handling Strings, say, you can replace the Object fields with String fields. For example, private static class SLink { String item; SLink next; SLink( String o, SLink n ) { item = o; next = n; } SLink( String o ) { this( o, null ); } } public void addFirst( String o );

The SLinkedList Data Members Only first is necessary. last and length could be found by traversing the list, but having these members and keeping them up to date makes the calls size() and addXXX() faster. Implementations vary on this point. private int length = 0; private SLink first = null; private SLink last = null;

== vs the Object equals method contains( Object o ) and remove( Object o ) must search for Object o in the list. What does it means to find it? Must the list contain a reference to the identical object ( == )? Or is it sufficient that the list contain a reference to an object that is equal but possibly distinct? static private boolean objectEquals( Object a, Object b ) { if ( a == null ) return ( b == null ); else return a.equals( b ); } Not in our Link class

Beware the Special Case The tricky part about implementing a linked list is not implementing the normal case for each of the methods, for instance, removing an object from the middle of the list. What's tricky is making sure that your methods will work in the exceptional and boundary cases. For each method, you should think through whether the implementation will work on –an empty list, –a list with only one or two elements, –on the first element of a list, –on the last element of a list.

removeFirst(), before List firstlast Link 1 Item 1 Link n Item 2 Item n... null Link 2

removeFirst(), after List firstlast Link 1 Item 1 Link n Item 2 Item n... null Link 2

removeFirst() public Object removeFirst() throws NoSuchElementException { if ( first == null ) // if list is empty throw new NoSuchElementException(); else { SLink t = first; first = first.next; // if list had 1 element and is now empty if ( first == null ) last = null; length--; return t.item; }

removeFirst(), special case List firstlast Link 1 Item 1 null before List firstlast Link 1 Item 1 null after

Exercise Write removeLast() –Draw pictures of the list before and after removing the last element –Handle the special cases where the list currently has: No elements One element

removeLast(), before List firstlast Link 1 Item 1 Link 3 Item 2 Item 3 null Link 2

removeLast(), after List firstlast Link 1 Item 1 Link 3 Item 2 Item 3 null Link 2 tt xx null ret

Solution public Object removeLast() throws NoSuchElementException { if (first == null) throw new NoSuchElementException(); else if (first == last) { // 1 element in list SLink t= first; first= last= null; length= 0; return t.item; } else { SLink t= first; while (t.next != last) t= t.next; Object ret= last.item; last= t; t.next= null; length--; return ret; } }

addFirst(Object o) public void addFirst(Object o) { if ( first == null ) // if the list is empty { first = last = new SLink( o ); } else { first = new SLink( o, first ); } length++; }

addFirst(), before List firstlast Link 1 Item 1 Link n Item n... null

addFirst(), after List firstlast Link 1 Item 1 Link n Item n... null Link 0 Item 0

addFirst(), special case List firstlast Link 1 Item 1 null before List firstlast null after

Exercise Write addLast(): –Draw a picture of the list before and after –Handle the special case of a currently empty list

Solution public void addLast(Object o) { // if the list is empty if ( first == null ) first = last = new SLink( o ); else last = last.next = new SLink( o ); length++; }

contains() public boolean contains(Object o) { boolean found= false; if (first == null) return false; SLink t= first; while (t != null) { if (objectEquals(t.item, o)) { found= true; break; } t= t.next; } return found; }

Other methods public int size() { return length; } public boolean isEmpty() { return( first == null ); } public void clear() { first = last = null; length = 0; }

Exercise Write the print() method –Check if list is empty –Otherwise walk the list and print out each item

Solution public void print() { if (first== null) { System.out.println("List is empty "); return; } SLink t= first; System.out.println("List contains: "); while (t != null) { System.out.print(t.item + " "); t= t.next; } System.out.println(); return; }

Main method public class ListMain { public static void main(String[] args) { SLinkedList a= new SLinkedList(); while (true) { String text= JOptionPane.showInputDialog("Enter 1-addFirst, 2- addLast, 3-removeFirst, 4-removeLast, 5-contains, 6- quit: "); int action= Integer.parseInt(text); if (action == 6) break; if (action== 1 || action== 2) text= JOptionPane.showInputDialog("Enter string to store in list: ");

Main method, p.2 if (action == 5) text= JOptionPane.showInputDialog("Enter string to find "); if (action == 1) a.addFirst(text); else if (action == 2) a.addLast(text); else if (action == 3) a.removeFirst(); else if (action== 4) a.removeLast(); else System.out.println("List has " + text + " ? " + a.contains(text)); a.print(); } System.exit(0); } }

Linked List Uses and Variations Since our List interface possesses appendLast() and removeFirst() methods you can implement a trivial queue on top of the SLinkedList concrete data type. How would the implementation be changed if each link had a back reference (previous) as well as a forward reference (next)? Such lists are called (you guessed it) doubly linked lists. What operations become easier?

Linked List Summary Linked list double ended queue –Implementation as SLink and SLinkedList classes SLink class is inner class of SLinkedList Can implement stacks, queues, trees as linked lists or arrays

Review - Linked List A simple way to collect a series of objects Each Object or link refers to the next Two examples: general and customized linked lists

Linked List Example 1: General SLink next obj SLink next obj SLink next obj null Object 1Object 2Object 3 class SLinkedList { SLink head; //add, delete, isEmpty, etc.; } class SLink { SLink next; Object obj; }

Linked List Example 2: Customized Link and data are combined into one class Less general, but easier to program null JavaStudent next name … class ListOfStudents { JavaStudent head; //add, delete, etc. } class JavaStudent { JavaStudent next; String name; int[] quizGrades; int[] psetGrades; } JavaStudent next name … JavaStudent next name …