Linked Lists Linear collections.

Slides:



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

Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
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.
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.
Queues and Linked Lists
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
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)
COMP 121 Week 9: AbstractList and ArrayList. Objectives List common operations and properties of Lists as distinct from Collections Extend the AbstractCollection.
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 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.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
David Weinberg presents Linked Lists: The Background  Linked Lists are similar to ArrayLists in their appearance and method of manipulation  They do.
CHAPTER 7 Queues.
Queues 4/14/2017 5:24 PM 5.2 Queues Queues Dr Zeinab Eid.
1 Queues (5.2) CSE 2011 Winter May Announcements York Programming Contest Link also available from.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
COMP 103 Linked Stack and Linked Queue.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
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.
1 Lecture 26 Abstract Data Types – IV Overview  The List ADT  Implementing Stacks as Linked List  Linked List Implementation of Queues .  Preview:
Review 1 Introduction Representation of Linear Array In Memory Operations on linear Arrays Traverse Insert Delete Example.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
The Java Collections Framework (JCF) Introduction and review 1.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
LinkedList Many slides from Horstmann modified by Dr V.
Queue FIFO (First In First Out) Java Doc peek, element offer poll, add
ليست هاي پيوندي Linked Lists ساختمان داده ها و الگوريتم ها.
Lab 7 Queue ADT. OVERVIEW The queue is one example of a constrained linear data structure. The elements in a queue are ordered from least recently added.
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.
(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.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Week 4 - Monday.  What did we talk about last time?  Queues  Implementing queues with circular arrays.
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
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.
Ordered Linked Lists using Abstract Data Types (ADT) in Java Presented by: Andrew Aken.
Chapter 5 Linked Lists II
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
Lists and Iterators Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented Programming.
List Interface and Linked List Mrs. Furman March 25, 2010.
Recursive Objects (Part 2) 1. Adding to the front of the list  adding to the front of the list  t.addFirst('z') or t.add(0, 'z') 2 'a' 'x' LinkedList.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
LINKED LIST’S EXAMPLES Salim Malakouti. Linked List? 523 Pointer Node ValuePointer.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Introduction Dynamic Data Structures Grow and shrink at execution time Linked lists are dynamic structures where data items are “linked up in a chain”
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 18 List ADT Animated Version.
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 9 Doubly Linked Lists and Ordered Lists Lecture.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
1 CS162: Introduction to Computer Science II Abstract Data Types.
CSCI 62 Data Structures Dr. Joshua Stough September 23, 2008.
The List ADT.
Java Methods Lists and Iterators Object-Oriented Programming
Week 3 - Friday CS221.
Programming in Java Lecture 11: ArrayList
Computer Science and Engineering
Collections Framework
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
Programming II (CS300) Chapter 07: Linked Lists
TCSS 143, Autumn 2004 Lecture Notes
Data Structures & Programming
Presentation transcript:

Linked Lists Linear collections

List Abstract Data Type List interface built-in to the collections framework The built-in List interface is a dynamic linear collection that DOES support random access This presentation uses a “simplified” List interface Our list is NOT the built-in list! Our list does NOT support random access Our list is dynamic (grows/shrinks as needed)

Java List Interface (Partial listing) void add(int index, Object element) - Inserts the specified element at the specified position in this list boolean add(Object element) - Appends the specified element to the end of this List. boolean addAll(int index, Collection c) - Inserts all of the elements in the specified collection into this list at the specified position. void clear() – Removes all elements from the list boolean equals(Object element) – Compares the specified object with this list for equality Object get(int index) – Returns the element at the specified index int indexOf(Object element) – Returns the index of the first occurrence of this object in the list boolean isEmpty() – Returns true if this list contains no elements and false otherwise Iterator iterator() – Returns an iterator over the elements of the list int lastIndexOf(Object element) – Returns the index of the last occurrence of element in the list Object remove(int index) – Removes and returns the element at the specified index Object set(int index, Object element) – Replaces the item at the specified index with the specified object int size() – Returns the number of elements in the list

Our List Interface Fundamental Methods void addToFront(Object d) Adds object d to the front of the list void addToTail(Object d) Adds object d to the end of the list Object removeFirst() Removes and returns the first element of the list An error occurs if the list is empty Object removeLast() Removes and returns the last element of the list Object first() Returns the first element of the list Object last() Returns the last element of the list interface List{ public void addToFront(Object o); public void addToTail(Object o); public Object removeFirst(); public Object removeLast(); public Object first(); public Object last(); public int size(); public boolean isEmpty(); }

List ADT Operation Output List theList.addToFront(“A”) none (“A”) theList.addToFront(“B”) none (“B”, “A”) theList.addToFront(“X”) none (“X”,”B”,”A”) theList.addToTail(“Y”) none (“X”,”B”,”A”,”Y”) theList.first() “X” (“X”,”B”,”A”,”Y”) theList.first() “X” (“X”,”B”,”A”,”Y”) theList.last() “Y” (“X”,”B”,”A”,”Y”) theList.removeFirst() “X” (“B”,”A”,”Y”) theList.removeLast() “Y” (“B”,”A”) theList.removeLast() “A” (“B”) theList.removeLast() “B” () theList.removeLast() error ()

List Implementation data: size: 5 Sequential Implementation (using arrays) Use an array to hold data elements Has a “fixed” capacity with (probably many) wasted slots. Insertion at the “beginning” of the list is slow (linear or O(n) performance). Keep track of the size of the list explicitly. Identical to a Vector index 0 index 11 Data Objects data: size: 5 List Object

Java Vector Class Hierarchy AbstractList AbstractCollection Object List Interface Collection Interface

Array List Performance Method Run-time performance void add(int index, Object element) O(n) boolean add(Object element) O(1) void clear() O(1) or O(n) Object get(int index) int indexOf(Object element) Object remove(int index) Object set(int index, Object element)

List Implementation head Next Data Next Data Next Data Singly-Linked Implementation: Uses a recursively-defined “list node” structure to hold data elements Keep track of only the “head” node and can access all other nodes by following a “link” to the “next” node Insertions and removals are done by changing the links. No shifting of data is ever required head List Object Next Data Node Object Data Object Next Data Next Data

Singly Linked List Each node is a “link” in a chain of “nodes”. class SListNode { private SListNode next; private Object data; SListNode(Object d) { data = d; next = null; } SListNode(Object d, SListNode n) { next = n; public SListNode getNext() { return next; public Object getData() { return data; public void setNext(SListNode n) { public void setData(Object d) { Each node is a “link” in a chain of “nodes”. Each node can only see “forward”. Each node contains a data element.

Singly Linked List class SinglyLinkedList implements List{ private SListNode head; private int size; SinglyLinkedList() { head = null; size = 0; } public void addToFront(Object o) { … public void addToTail(Object o) { public Object removeFirst() { public Object removeLast() { interface List{ public void addToFront(Object o); public void addToTail(Object o); public Object removeFirst(); public Object removeLast(); public Object first(); public Object last(); public int size(); public boolean isEmpty(); } The list keeps track of the first link (called the “head”) from which all other links can be accessed.

Singly Linked List Insertion Inserting an item means changing links (not shifting data) How do we insert an item at the front of this list? Next Data Node Object Data Object head List Object Next Data

Singly Linked List Insertion public void addToFront(Object o) { head = new SListNode(o, head); size++; } Show me the code! head List Object Next Data Node Object Data Object

Singly Linked List Removal Removing an item means changing links (not shifting data) How do we remove an item from the front of this list? head List Object Next Data Node Object Data Object

Singly Linked List Removal public Object removeFirst() { if(isEmpty()) { throw new NoSuchElementException(); } SListNode node = head; head = head.getNext(); size--; return node.getData(); nullPointerException! Aaargh!!! head List Object Next Data Node Object Data Object

Singly Linked List Example (lists are entertaining and fun!) List list = new SinglyLinkedList(); for(int i=0; i<3; i++) { list.addToFront(new Integer(i)); } while(!list.isEmpty()) { System.out.println(list.removeFirst()); public void addToFront(Object o) { head = new SListNode(o, head); size++; } public Object removeFirst() { if(isEmpty()) { throw new NoSuchElementException(); } SListNode node = head; head = head.getNext(); size--; return node.getData();

Linked List Insertion head What needs to happen to insert at the end of this list? Inserting at the end means changing the link of the last node! Since we only “know” about the first node we have to navigate through the list until the last node is found. We then change its link. head List Object Next Data Node Object Data Object Next Data Next Data

Singly Linked List Insertion Inserting at the end means changing the link of the last node! Since we only “know” about the first node we have to navigate through the list until the last node is found. We then change its link. public void addToTail(Object value) { SListNode newNode = new SListNode(value, null); if(isEmpty()) { head = newNode; } else { SListNode n = head; while(n.getNext() != null) { n = n.getNext(); } n.setNext(newNode); size++; Um, Ah, ?, …, getNext!

Singly Linked List Removal Removing at the end means changing the link of the second-to-last node! Since we only “know” about the first node we have to navigate through the list until the second-to-last node is found. We then change its link. public Object removeLast() { if(isEmpty()) { throw new NoSuchElementException(); } SListNode tmp = head, prev = null; while(tmp.getNext() != null) { prev = tmp; tmp = tmp.getNext(); if(prev == null) { head = null; } else { prev.setNext(null); size--; return tmp.getData();

Singly Linked List Example (lists are entertaining and fun!) List list = new SinglyLinkedList(); for(int i=0; i<3; i++) { list.addToTail(new Integer(i)); } while(!list.isEmpty()) { System.out.println(list.removeLast()); public void addToTail(Object value) { SListNode newNode = new SListNode(value, null); if(isEmpty()) { head = newNode; } else { SListNode n = head; while(n.getNext() != null) { n = n.getNext(); } n.setNext(newNode); size++;

Singly Linked List Example (lists are entertaining and fun!) List list = new SinglyLinkedList(); for(int i=0; i<3; i++) { list.addToTail(new Integer(i)); } while(!list.isEmpty()) { System.out.println(list.removeLast()); public Object removeLast() { if(isEmpty()) { throw new NoSuchElementException(); } SListNode tmp = head, prev = null; while(tmp.getNext() != null) { prev = tmp; tmp = tmp.getNext(); if(prev == null) { head = null; } else { prev.setNext(null); size--; return tmp.getData();

Singly Linked List Variations There are variations on implementation that make coding somewhat simpler use a sentinel node as the head to simplify the code (doesn’t do much for singly-linked lists) sentinel node is always present (even in an empty list) sentinel node stores no data sentinel node serves only as a “bookend” public SinglyLinkedList implements List { private SListNode head; private int size; SinglyLinkedList() { head = new SListNode(null, null); size = 0; } … If in an empty list head is not null then the list uses sentinel nodes.

Sentinal Node Example Sentinel Nodes No Sentinel Nodes public void addToFront(Object o) { head.setNext(new SListNode(o, head.getNext()); size++; } public void addToFront(Object o) { head = new SListNode(o, head); size++; } Sentinel Nodes No Sentinel Nodes public Object removeFirst() { if(isEmpty()) { throw new NoSuchElementException(); } SListNode node = head.getNext(); head.setNext(head.getNext().getNext()); size--; return node.getData(); public Object removeFirst() { if(isEmpty()) { throw new NoSuchElementException(); } SListNode node = head; head = head.getNext(); size--; return node.getData();

Singly-Linked List Performance Method Run-time performance void add(int index, Object element) O(n) boolean add(Object element) O(1) void clear() Object get(int index) int indexOf(Object element) Object remove(int index) Object set(int index, Object element)

List Implementation Next Next Next Prev Prev Prev Data Data Data Doubly-Linked Implementation: Uses a recursively-defined “list node” structure to hold data elements Has dynamic capacity with little “wasted” memory Keep track of the “head” and “tail” nodes and can access all other nodes “Natural” operations are from the head and tail since they are “fast” Head Node Tail Node Next Next Next Prev Prev Prev Data Data Data

Doubly Linked List Each node is a “link” in a chain of “nodes”. class DListNode { private DListNode previous, next; private Object data; DListNode(Object d) { data = d; next = null; previous = null; } DListNode(Object d, DListNode p, DListNode n) { previous = p; next = n; // accessors and mutators Each node is a “link” in a chain of “nodes”. Each node can see “forward” AND “backward” Each node contains a data element.

Doubly Linked List class DoublyLinkedList implements List{ private DListNode head, tail; private int size; DoublyLinkedList() { head = null; tail = null; size = 0; } public void addToFront(Object o) { … public void addToTail(Object o) { public Object removeFirst() { public Object removeLast() { // other methods interface List{ public void addToFront(Object o); public void addToTail(Object o); public Object removeFirst(); public Object removeLast(); public Object first(); public Object last(); public int size(); public boolean isEmpty(); } The list keeps track of the first link (called the “head”) from which all other links can be accessed.

Add To Front Operation public void addToFront(Object o) { head = new DListNode(o, null, head); if(head.getNext() != null) { head.getNext().setPrevious(head); } if(tail == null) tail = head; size++; What needs to be done to insert an item at the head of this list? tail head size: 3 Next Prev Head Node Data Tail Node

Remove First Operation public Object removeFirst() { if(isEmpty()) { throw new NoSuchElementException(); } Object result = head.getData(); head = head.getNext(); if(head != null) { head.setPrevious(null); } else { tail = null; size--; return result; What needs to be done to remove an item at the head of this list? tail head size: 3 Next Prev Data

Front Operations Example public void addToFront(Object o) { head = new DListNode(o, null, head); if(head.getNext() != null) { head.getNext().setPrevious(head); } if(tail == null) tail = head; size++; public Object removeFirst() { if(isEmpty()) { throw new NoSuchElementException(); } Object result = head.getData(); head = head.getNext(); if(head != null) { head.setPrevious(null); } else { tail = null; size--; return result; List list = new DoublyLinkedList(); for(int i=0; i<3; i++) { list.addToFront(new Integer(i)); } while(!list.isEmpty()) { System.out.println(list.removeFirst());

Add To Tail Operation public void addToFront(Object o) { head = new DListNode(o, null, head); if(head.getNext() != null) { head.getNext().setPrevious(head); } if(tail == null) tail = head; size++; Since it is a doubly-linked list – the list “looks” the same both forward and backward. The methods are symmetrical! public void addToTail(Object o) { tail = new DListNode(o, tail, null); if(tail.getPrevious() != null) { tail.getPrevious().setNext(tail); } if(head == null) head = tail; size++;

Remove From Tail Operation public Object removeFirst() { if(isEmpty()) { throw new NoSuchElementException(); } Object result = head.getData(); head = head.getNext(); if(head != null) { head.setPrevious(null); } else { tail = null; size--; return result; public Object removeLast() { if(isEmpty()) { throw new NoSuchElementException(); } Object result = tail.getData(); tail = tail.getPrevious(); if(tail != null) { tail.setNext(null); } else { head = null; size--; return result; The remove methods are also highly symmetrical.

Tail Operations Example public Object removeLast() { if(isEmpty()) { throw new NoSuchElementException(); } Object result = tail.getData(); tail = tail.getPrevious(); if(tail != null) { tail.setNext(null); } else { head = null; size--; return result; public void addToTail(Object o) { tail = new DListNode(o, tail, null); if(tail.getPrevious() != null) { tail.getPrevious().setNext(tail); } if(head == null) head = tail; size++; List list = new DoublyLinkedList(); for(int i=0; i<3; i++) { list.addToTail(new Integer(i)); } while(!list.isEmpty()) { System.out.println(list.removeLast());

Doubly-Linked List Performance Method Run-time performance void add(int index, Object element) O(n) boolean add(Object element) O(1) void clear() Object get(int index) int indexOf(Object element) Object remove(int index) Object set(int index, Object element)

List Implementation Next Next Next Prev Prev Prev Data Data Data Sentinel nodes: Implementation technique to simplify the code Can be used with either doubly or singly linked lists Head (and tail) nodes are “dummy” nodes that hold no data Head (and tail) nodes never change and are always present Head Node Tail Node Next Next Next Prev Prev Prev Data Data Data “Sentinel” nodes contain no data

A Simple Problem Problem: Given a List – write a method to print the contents of the list without modifying the list! interface List{ public void addToFront(Object o); public void addToTail(Object o); public Object removeFirst(); public Object removeLast(); public Object first(); public Object last(); public int size(); public boolean isEmpty(); } public void printList(List list) { for(int i=0; i<list.size(); i++) { Object tmp = list.removeFirst(); System.out.println(tmp); list.addToTail(tmp); }

Enumerations!!! A better solution is to use an Enumeration An interface in the “java.util” package Gives sequential read-only access to the contents of a linear collection Don’t need to know anything about the collection implementation interface Enumeration { public boolean hasMoreElements(); public Object nextElement(); } public void printList(List list) { Enumeration e = list.elements(); while(e.hasMoreElements()) { System.out.println(e.nextElement()); }

Enumeration class SinglyLinkedListEnumeration implements Enumeration { class SinglyLinkedList implements List { private SListNode head; private int size; // other methods here Enumeration elements() { … } class SinglyLinkedListEnumeration implements Enumeration { private SListNode current; SinglyLinkedListEnumeration(SListNode n) { current = n; } public boolean hasMoreElements() { return current != null; public Object nextElement() { if(!hasMoreElements()) { throw new NoSuchElementException(); Object result = current.getData(); current = current.getNext(); return result;

Java LinkedList Class Hierarchy AbstractSequentialList AbstractList AbstractCollection Object