COS 312 DAY 21 Tony Gauvin. Ch 1 -2 Agenda Questions? Last Capstone Progress reports due April 23 Assignment 6 Due Assignment 7 Posted – Chapters 15,

Slides:



Advertisements
Similar presentations
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.
Advertisements

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 15 Lists. Chapter Scope Types of list collections Using lists to solve problems Various list implementations Comparing list implementations Java.
1 Lists A List ADT Types of Lists Lists in Java Collections API Using ordered lists – Tournament Maker Using indexed lists – Josephus Problem Implementing.
Topic 9 The Queue ADT.
CHAPTER 7 Queues.
Chapter 7 Queues. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine queue processing Define a queue abstract.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Chapter 14 Queues. Chapter Scope Queue processing Using queues to solve problems Various queue implementations Comparing queue implementations Java Foundations,
Chapter 7 Iterators Modified. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using.
1 Lists A List ADT Types of Lists Lists in Java Collections API Using ordered lists – Tournament Maker Using indexed lists – Josephus Problem Implementing.
Chapter 15 Lists.
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.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
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.
Chapter 8 Lists. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 8-2 Chapter Objectives Examine list processing and various ordering techniques.
Chapter 13 Linked Structures - Stacks. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked implementation.
Chapter 22 Sets and Maps. Chapter Scope The Java API set and map collections Using sets and maps to solve problems How the Java API implements sets and.
Chapter 14 Queues. First a Review Queue processing Using queues to solve problems – Optimizing customer service simulation – Ceasar ciphers – Palindrome.
Chapter 4 Linked Structures – Stacks Modified. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked.
Chapter 12 Introduction to Collections - Stacks
Topic 3 The Stack ADT.
Chapter 3 Introduction to Collections – Stacks Modified
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.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 10: Binary Search Trees Java Software Structures: Designing.
Trees CSCI Objectives Define trees as data structures Define the terms associated with trees Discuss the possible implementations of trees Analyze.
Chapter 10-A Trees Modified
COS 312 DAY 20 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 – Questions? Queues.
LinkedList Many slides from Horstmann modified by Dr V.
Chapter 20 Binary Search Trees
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 5: Queues Java Software Structures: Designing and Using Data.
Linked Structures - Review Chapter 13 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Chapter 2 Collections. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Define the concept and terminology related.
Chapter 3 Collections. Objectives  Define the concepts and terminology related to collections  Explore the basic structures of the Java Collections.
COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.
Chapter 6 Lists Modified. Chapter Scope Types of lists Using lists to solve problems Various list implementations Comparing list implementations 6 - 2Java.
Collections Chapter 12 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
COS 312 DAY 18 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 5 Corrected – 1 A, 2 B’s, 1 C, 1 D 1 F and 1 MIA –
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
Linked Structures Chapter 13 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
COS 312 DAY 23 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone progress report Overdue Assignment 6 Over Due Assignment 7 (bonus) – Due May 11 – Will.
Collections & Stacks Collections A collection is an object that holds and organizes other objects It provides operations for accessing and managing.
Iterators. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using iterators to solve.
1 Iterators & the Collection Classes. 2 » The Collection Framework classes provided in the JAVA API(Application Programmer Interface) contains many type.
Linked Structures - Stacks. Linked Structures An alternative to array-based implementations are linked structures A linked structure uses object references.
The List ADT.
Lists A List ADT Types of Lists Using ordered lists – Tournament Maker
COS 312 DAY 21 Tony Gauvin.
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Chapter 16 Iterators.
Chapter 21 Heaps and Priority Queues
Chapter 6 Lists.
Top Ten Words that Almost Rhyme with “Peas”
Chapter 4 Linked Structures - Stacks
Chapter 5 Queues.
Chapter 7 Iterators.
Java Software Structures: John Lewis & Joseph Chase
Chapter 4 Linked Structures - Stacks
Java Software Structures: John Lewis & Joseph Chase
Programming II (CS300) Chapter 07: Linked Lists and Iterators
CHAPTER 11: Priority Queues and Heaps
Chapter 20 Binary Search Trees
Chapter 21 Heaps and Priority Queues
CHAPTER 3: Collections—Stacks
Presentation transcript:

COS 312 DAY 21 Tony Gauvin

Ch 1 -2 Agenda Questions? Last Capstone Progress reports due April 23 Assignment 6 Due Assignment 7 Posted – Chapters 15, 17 & 18 – Due April 30 – 20 point Bonus Program Lists

Final Countdown Today – Lists – Assignment 6 due April 20 – Iterators – Course Evaluations April 23 – Recursion – Capstone Progress report due April 27 – Searching and sorting April 30 – Trees – Assignment 7 due May 1 PM – Capstone Presentations – Quiz 3 Java Foundations, 3rd Edition, Lewis/DePasquale/Chase5 - 3

Chapter 15 Lists

Chapter Scope Types of list collections Using lists to solve problems Various list implementations Comparing list implementations Java Foundations, 3rd Edition, Lewis/DePasquale/Chase15 - 5

Lists A list is a linear collection, like stacks and queues, but is more flexible Adding and removing elements in lists can occur at either end or anywhere in the middle We will examine three types of list collections: – ordered lists (sorted) – unordered lists (not sorted) – indexed lists (have a numeric index) Java Foundations, 3rd Edition, Lewis/DePasquale/Chase15 - 6

Ordered Lists The elements in an ordered list are ordered by some inherent characteristic of the elements – names in alphabetical order – scores in ascending order The elements themselves determine where they are stored in the list Java Foundations, 3rd Edition, Lewis/DePasquale/Chase15 - 7

Ordered Lists An ordered list: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase15 - 8

Unordered Lists There is an order to the elements in an unordered list, but that order is not based on element characteristics The user of the list determines the order of the elements A new element can be put on the front or the rear of the list, or it can be inserted after a particular element already in the list Java Foundations, 3rd Edition, Lewis/DePasquale/Chase15 - 9

Unordered Lists An unordered list: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Indexed Lists In an indexed list, elements are referenced by their numeric position in the list Like an unordered list, there is no inherent relationship among the elements The user can determine the order Every time the list changes, the indexes are updated << requires O(n) extra computing cycles Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Indexed Lists An indexed list: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Lists in the Java API The list classes in the Java API primarily support the concept of an indexed list (and somewhat an unordered list) The API does not have any classes that directly implement an ordered list The ArrayList and LinkedList classes both implement the List interface – html html – edList.html edList.html – List.html List.html Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Lists in the Java API Some of the operations from the List interface: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Program of Study Let's use an unordered list to manage the courses that a student takes to fulfill degree requirements The Course class represents a course, which may or may not have already been taken The ProgramOfStudy class manages a list of Course objects The list is stored for later use using serialization – serial.html serial.html Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.io.Serializable; /** * Represents a course that might be taken by a student. * Java Foundations 4.0 */ public class Course implements Serializable { private String prefix; private int number; private String title; private String grade; Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Constructs the course with the specified information. * prefix the prefix of the course designation number the number of the course designation title the title of the course grade the grade received for the course */ public Course(String prefix, int number, String title, String grade) { this.prefix = prefix; this.number = number; this.title = title; if (grade == null) this.grade = ""; else this.grade = grade; } /** * Constructs the course with the specified information, with no grade * established. * prefix the prefix of the course designation number the number of the course designation title the title of the course */ public Course(String prefix, int number, String title) { this(prefix, number, title, ""); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns the prefix of the course designation. * the prefix of the course designation */ public String getPrefix() { return prefix; } /** * Returns the number of the course designation. * the number of the course designation */ public int getNumber() { return number; } /** * Returns the title of this course. * the prefix of the course */ public String getTitle() { return title; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns the grade for this course. * the grade for this course */ public String getGrade() { return grade; } /** * Sets the grade for this course to the one specified. * grade the new grade for the course */ public void setGrade(String grade) { this.grade = grade; } /** * Returns true if this course has been taken (if a grade has been received). * true if this course has been taken and false otherwise */ public boolean taken() { return !grade.equals(""); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Determines if this course is equal to the one specified, based on the * course designation (prefix and number). * true if this course is equal to the parameter */ public boolean equals(Object other) { boolean result = false; if (other instanceof Course) { Course otherCourse = (Course) other; if (prefix.equals(otherCourse.getPrefix()) && number == otherCourse.getNumber()) result = true; } return result; } /** * Creates and returns a string representation of this course. * a string representation of the course */ public String toString() { String result = prefix + " " + number + ": " + title; if (!grade.equals("")) result += " [" + grade + "]"; return result; } Code\chap15\Course.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Represents a Program of Study, a list of courses taken and planned, for an * individual student. * Java Foundations 4.0 */ public class ProgramOfStudy implements Iterable, Serializable { private List list; /** * Constructs an initially empty Program of Study. */ public ProgramOfStudy() { list = new LinkedList (); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Adds the specified course to the end of the course list. * course the course to add */ public void addCourse(Course course) { if (course != null) list.add(course); } /** * Finds and returns the course matching the specified prefix and number. * prefix the prefix of the target course number the number of the target course the course, or null if not found */ public Course find(String prefix, int number) { for (Course course : list) if (prefix.equals(course.getPrefix()) && number == course.getNumber()) return course; return null; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Adds the specified course after the target course. Does nothing if * either course is null or if the target is not found. * target the course after which the new course will be added newCourse the course to add */ public void addCourseAfter(Course target, Course newCourse) { if (target == null || newCourse == null) return; int targetIndex = list.indexOf(target); if (targetIndex != -1) list.add(targetIndex + 1, newCourse); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Replaces the specified target course with the new course. Does nothing if * either course is null or if the target is not found. * target the course to be replaced newCourse the new course to add */ public void replace(Course target, Course newCourse) { if (target == null || newCourse == null) return; int targetIndex = list.indexOf(target); if (targetIndex != -1) list.set(targetIndex, newCourse); } /** * Creates and returns a string representation of this Program of Study. * a string representation of the Program of Study */ public String toString() { String result = ""; for (Course course : list) result += course + "\n"; return result; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns an iterator for this Program of Study. * an iterator for the Program of Study */ public Iterator iterator() { return list.iterator(); } /** * Saves a serialized version of this Program of Study to the specified * file name. * fileName the file name under which the POS will be stored IOException */ public void save(String fileName) throws IOException { FileOutputStream fos = new FileOutputStream(fileName); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(this); oos.flush(); oos.close(); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Loads a serialized Program of Study from the specified file. * fileName the file from which the POS is read the loaded Program of Study IOException ClassNotFoundException */ public static ProgramOfStudy load(String fileName) throws IOException, ClassNotFoundException { FileInputStream fis = new FileInputStream(fileName); ObjectInputStream ois = new ObjectInputStream(fis); ProgramOfStudy pos = (ProgramOfStudy) ois.readObject(); ois.close(); return pos; } Code\chap15\ProgramOfStudy.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.io.IOException; /** * Demonstrates the use of a list to manage a set of objects. * Java Foundations 4.0 */ public class POSTester { /** * Creates and populates a Program of Study. Then saves it using serialization. */ public static void main(String[] args) throws IOException { ProgramOfStudy pos = new ProgramOfStudy(); pos.addCourse(new Course("CS", 101, "Introduction to Programming", "A-")); pos.addCourse(new Course("ARCH", 305, "Building Analysis", "A")); pos.addCourse(new Course("GER", 210, "Intermediate German")); pos.addCourse(new Course("CS", 320, "Computer Architecture")); pos.addCourse(new Course("THE", 201, "The Theatre Experience")); Course arch = pos.find("CS", 320); pos.addCourseAfter(arch, new Course("CS", 321, "Operating Systems")); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Course theatre = pos.find("THE", 201); theatre.setGrade("A-"); Course german = pos.find("GER", 210); pos.replace(german, new Course("FRE", 110, "Beginning French", "B+")); System.out.println(pos); pos.save("ProgramOfStudy"); } Code\chap15\POSTester.java Code\chap15\POSLoad.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Serialization Any class whose objects will be saved are tagged with the Serializable interface Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

xxx Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

The Josephus Problem In a Josephus problem, a set of elements are arranged in a circle Starting with a particular element, every i th element is removed Processing continues until there is only one element left The question: given the starting point and remove count (i), which element is left? Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Josephus N= 12, Move is 3 Java Foundations, 3rd Edition, Lewis/DePasquale/Chase Source:

import java.util.*; /** * Demonstrates the use of an indexed list to solve the Josephus problem. * Java Foundations 4.0 */ public class Josephus { /** * Continue around the circle eliminating every nth soldier * until all of the soldiers have been eliminated. */ public static void main(String[] args) { int numPeople, skip, targetIndex; List list = new ArrayList (); Scanner in = new Scanner(System.in); // get the initial number of soldiers System.out.print("Enter the number of soldiers: "); numPeople = in.nextInt(); in.nextLine(); // get the number of soldiers to skip System.out.print("Enter the number of soldiers to skip: "); skip = in.nextInt(); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

// load the initial list of soldiers for (int count = 1; count <= numPeople; count++) { list.add("Soldier " + count); } targetIndex = skip; System.out.println("The order is: "); // Treating the list as circular, remove every nth element // until the list is empty while (!list.isEmpty()) { System.out.println(list.remove(targetIndex)); if (list.size() > 0) targetIndex = (targetIndex + skip) % list.size(); } Code\chap15\Josephus.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing Lists Now let's implement our own list collection The following operations are common to all types of lists: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing Lists Operation particular to an ordered list: Operations particular to an unordered lists: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

xxx Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

package jsjf; import java.util.Iterator; /** * ListADT defines the interface to a general list collection. Specific * types of lists will extend this interface to complete the * set of necessary operations. * Java Foundations 4.0 */ public interface ListADT extends Iterable { /** * Removes and returns the first element from this list. * the first element from this list */ public T removeFirst(); /** * Removes and returns the last element from this list. * the last element from this list */ public T removeLast(); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Removes and returns the specified element from this list. * element the element to be removed from the list */ public T remove(T element); /** * Returns a reference to the first element in this list. * a reference to the first element in this list */ public T first(); /** * Returns a reference to the last element in this list. * a reference to the last element in this list */ public T last(); /** * Returns true if this list contains the specified target element. * target the target that is being sought in the list true if the list contains this element */ public boolean contains(T target); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns true if this list contains no elements. * true if this list contains no elements */ public boolean isEmpty(); /** * Returns the number of elements in this list. * the integer representation of number of elements in this list */ public int size(); /** * Returns an iterator for the elements in this list. * an iterator over the elements in this list */ public Iterator iterator(); /** * Returns a string representation of this list. * a string representation of this list */ public String toString(); } Code\chap15\jsjf\IndexedListADT.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

package jsjf; /** * OrderedListADT defines the interface to an ordered list collection. Only * Comparable elements are stored, kept in the order determined by * the inherent relationship among the elements. * Java Foundations 4.0 */ public interface OrderedListADT extends ListADT { /** * Adds the specified element to this list at the proper location * element the element to be added to this list */ public void add(T element); } Code\chap15\jsjf\OrderedListADT.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

package jsjf; /** * UnorderedListADT defines the interface to an unordered list collection. * Elements are stored in any order the user desires. * Java Foundations 4.0 */ public interface UnorderedListADT extends ListADT { /** * Adds the specified element to the front of this list. * element the element to be added to the front of this list */ public void addToFront(T element); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Adds the specified element to the rear of this list. * element the element to be added to the rear of this list */ public void addToRear(T element); /** * Adds the specified element after the specified target. * element the element to be added after the target target the target is the item that the element will be added * after */ public void addAfter(T element, T target); } Code\chap15\jsjf\UnorderedListADT.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a List with an Array Since elements can be added anywhere in the list, shifting elements cannot be avoided So a straightforward implementation can be adopted: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase Front 0 0

package jsjf; import jsjf.exceptions.*; import java.util.*; /** * ArrayList represents an array implementation of a list. The front of * the list is kept at array index 0. This class will be extended * to create a specific kind of list. * Java Foundations 4.0 */ public abstract class ArrayList implements ListADT, Iterable { private final static int DEFAULT_CAPACITY = 100; private final static int NOT_FOUND = -1; protected int rear; protected T[] list; protected int modCount; /** * Creates an empty list using the default capacity. */ public ArrayList() { this(DEFAULT_CAPACITY); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Creates an empty list using the specified capacity. * initialCapacity the integer value of the size of the array list */ public ArrayList(int initialCapacity) { rear = 0; list = (T[])(new Object[initialCapacity]); modCount = 0; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Removes and returns the specified element. * element the element to be removed and returned from the list the removed elememt ElementNotFoundException if the element is not in the list */ public T remove(T element) { T result; int index = find(element); if (index == NOT_FOUND) throw new ElementNotFoundException("ArrayList"); result = list[index]; rear--; // shift the appropriate elements for (int scan=index; scan < rear; scan++) list[scan] = list[scan+1]; list[rear] = null; modCount++; return result; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns true if this list contains the specified element. * target the target element true if the target is in the list, false otherwise */ public boolean contains(T target) { return (find(target) != NOT_FOUND); } /** * Returns the array index of the specified element, or the * constant NOT_FOUND if it is not found. * target the target element the index of the target element, or the * NOT_FOUND constant */ private int find(T target) { int scan = 0; int result = NOT_FOUND; if (!isEmpty()) while (result == NOT_FOUND && scan < rear) if (target.equals(list[scan])) result = scan; else scan++; return result; } Code\chap15\jsjf\ArrayList.javaCode\chap15\jsjf\ArrayList.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Adds the specified Comparable element to this list, keeping * the elements in sorted order. * element the element to be added to the list */ public void add(T element) { if (!(element instanceof Comparable)) throw new NonComparableElementException("OrderedList"); Comparable comparableElement = (Comparable )element; if (size() == list.length) expandCapacity(); int scan = 0; // find the insertion location while (scan 0) scan++; // shift existing elements up one for (int shift=rear; shift > scan; shift--) list[shift] = list[shift-1]; // insert element list[scan] = element; rear++; modCount++; } Code\chap15\jsjf\ArrayOrderedList.java Code\chap15\jsjf\ArrayOrderedList.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Adds the specified element after the specified target element. * Throws an ElementNotFoundException if the target is not found. * element the element to be added after the target element target the target that the element is to be added after */ public void addAfter(T element, T target) { if (size() == list.length) expandCapacity(); int scan = 0; // find the insertion point while (scan < rear && !target.equals(list[scan])) scan++; if (scan == rear) throw new ElementNotFoundException("UnorderedList"); scan++; // shift elements up one for (int shift=rear; shift > scan; shift--) list[shift] = list[shift-1]; // insert element list[scan] = element; rear++; modCount++; } Code\chap15\jsjf\ArrayUnorderedList.javaCode\chap15\jsjf\ArrayUnorderedList.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a List with Links A classic linked list is an obvious choice for implementing a list collection The LinearNode class introduced earlier is reused here Both head and tail references are maintained, as well as an integer count Code\chap15\jsjf\LinearNode.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

package jsjf; import jsjf.exceptions.*; import java.util.*; /** * LinkedList represents a linked implementation of a list. * Java Foundations 4.0 */ public abstract class LinkedList implements ListADT, Iterable { protected int count; protected LinearNode head, tail; protected int modCount; /** * Creates an empty list. */ public LinkedList() { count = 0; head = tail = null; modCount = 0; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Removes the first instance of the specified element from this * list and returns a reference to it. Throws an EmptyCollectionException * if the list is empty. Throws a ElementNotFoundException if the * specified element is not found in the list. * targetElement the element to be removed from the list a reference to the removed element EmptyCollectionException if the list is empty ElementNotFoundException if the target element is not found */ public T remove(T targetElement) throws EmptyCollectionException, ElementNotFoundException { if (isEmpty()) throw new EmptyCollectionException("LinkedList"); boolean found = false; LinearNode previous = null; LinearNode current = head; while (current != null && !found) if (targetElement.equals(current.getElement())) found = true; else { previous = current; current = current.getNext(); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

if (!found) throw new ElementNotFoundException("LinkedList"); if (size() == 1) // only one element in the list head = tail = null; else if (current.equals(head)) // target is at the head head = current.getNext(); else if (current.equals(tail)) // target is at the tail { tail = previous; tail.setNext(null); } else // target is in the middle previous.setNext(current.getNext()); count--; modCount++; return current.getElement(); } Code\chap15\jsjf\LinkedList.java Code\chap15\jsjf\LinkedOrderedList.java Code\chap15\jsjf\LinkedUnorderedList.java Code\chap15\OrderedLLTester.java Code\chap15\UnOrderedLLTester.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase