119
1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

Embed Size (px)

Citation preview

Page 1: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

1

Linked Lists

Starring:

Singly Linked List

ListNode

Doubly Linked List

Iterator

Co-Starring:

ListIterator

Page 2: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

2

Purpose:

In this lecture series we will learn about Linked Lists

Linked Lists are another type of Data Structure based off of the List Abstract Data Type.

Linked Lists provide advantages in terms of efficiency when certain types of actions need to be performed on the data.

Page 3: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

3

Resources:

Java Methods AB Data Structures Chapter 2 p.34 Java Essentials Chapter 19 p.737 Java Essentials Study Guide Chapter 16 p.263 Barrons Chapter 8 p.244 & Chapter 11 p.361 Big Java Chapter Chapter 19 p.737 Lambert Comprehensive Units 4 & 5 (chs 12-16) Taft Notes p.12 (old) & also in last summers

notes Taft Notes 2003

Page 4: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

4

Handouts:

1.Java Classes And Interfaces:

List

Linked List

Iterator

ListIterator

2.ListNode Class

3.Sample Code (UsingLinkedList.java & SampleLinkedList.java)

4.ListIterator Illustration JESG p.266-268 & p.269-280

Page 5: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

5

What we Will Cover in This Lecture:

The List Interface as it pertains to the ArrayList and Linked List Data Structures

Advantages and Drawbacks of the ArrayList Data Structure

Page 6: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

6

What we Will Cover in This Lecture:

The Need for an Alternate method of Data Storage

The Concept of the Linked List

The ListNode Class (Singly LL)

Page 7: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

7

What we Will Cover in This Lecture:

Behaviors of a Linked List: Create, Insert (Add) , Remove, Traverse (Iterate)

Singly, Doubly, Circular LL & LL with a Tail

Review Of Sample Code (Instructor)

Page 8: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

8

What we Will Cover in This Lecture:

TPS Create Your Own Linked List Class

Java’s LinkedList Class

Doubly LL

Page 9: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

9

What we Will Cover in This Lecture:

Iterator and ListIterator Classes

Iterating Thru a LinkedList (Java Class)

Big-O of a Linked List (compared to ArrayList)

The AP AB Requirements

Page 10: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

10

The List Interface

Lets Re-focus on the List Interface and then we will look at a class, LinkedList, that implements the List interface

Page 11: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

11

Page 12: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

12

This is merely a structure or a set of criteria that can be implemented different ways

We can have a LinkedList implementation of the Abstract List Structure. All we need to do is make sure we provide for the BEHAVIORS as specified in the Criteria for a List (add, remove, get, size, modify)

Page 13: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

13

Each implementation must be evaluated against their relative “costs” when deciding which one to use for a particular system

The List interface merely identifies the behaviors that MUST exist in a List

Page 14: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

14

The actual implementation of which is left to the specific data structure

As for the Iterator and ListIterator Interfaces, we will discuss these shortly

The List Interface requires you implement a Size and an Add Behavior

Page 15: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

15

The List also requires implementation of a ListIterator.

We will use this when we work with Java’s LinkedList class

Page 16: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

16

The ArrayList Data Structure’s Advantages and Drawbacks

Since Lists can be implemented as either an ArrayList or a LinkedList we need to discuss when we would select one over the other as each has strengths as well as limitations

Page 17: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

17

ArrayLists are good at direct access of the n-th element --- O(1)

This makes arrays excellent for a Binary Search as it requires direct access to the middle of an Array of elements

Page 18: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

18

LinkedLists, by their nature, do not provide direct access to specific Nodes because each element only knows about its previous or next Node. So access to a specific Node is a Linear operation --- O(n)

Page 19: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

19

Arrays are not good at inserting elements at the top or near the middle and are also not best used when the size of the list varies widely--- O(n)

Page 20: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

20

LinkedLists are best at insertion and removal of specific nodes as we merely have to rearrange the links --- O(1)

They are also good in situations where the size of the list is unknown as nodes are only allocated as needed, leading to no wasted memory

Page 21: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

21

You do not need to RESIZE a LinkedList

Page 22: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

22

Therefore, when the data being stored is static and its size is known an Array is a better choice because its weaknesses are minimized and its strengths compliment the dominant process of searching the data --- Log(n)

Page 23: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

23

In situations where the size and content of the data vary to a point where these operations become the dominant process a LinkedList is preferred

This is because the insertion and removal are efficient , O(1), and we can live with sporadic searches --- O(n)

Page 24: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

24

Alternate List Implementation (Linked List)

We can think of an Array or an ArrayList as a book

A Book is a contiguous set of elements indexed by page numbers

We can read through the book page by page or we can open it directly to any part of the book

That’s what a book is best at doing

Page 25: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

25

However, we can not easily insert a new page into an existing book as we would have to rearrange the pages that follow the insert

Also, if the book becomes too big for its bindings, we would need to transfer the pages to a Bigger one

Page 26: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

26

We can think of a LinkedList as a magazine article

The article appears “in parts” scattered throughout the book

We need to know where the first “part” of the article is

Page 27: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

27

Then at the end of each “part” we are told where the next “part” is

We only know when the article is completed when it says “END” at the end of the last “part”

Page 28: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

28

Since the article is spread out, it is not a problem to insert a new piece to the story

It is also easy to remove a part of the story

However, we can only get to a specific “part” of the story by traversing the entire article from the beginning

Page 29: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

29

The Conceptual Linked List

More formally, an element of a Linked List is a called a “node”

Each node contains information plus a pointer to the next node

The nodes provide REFERENCES to another node

Page 30: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

30

We know a Linked List ends when its last node points to nothing (NULL)

ILLUSTRATION:

Given a class called AirFLight that contains a flight destination and a flight number we could construct the following Data Link:

Page 31: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

31

“Head” of the Link is at OC1

ATLANTA #100 ORLANDO #500 KENNEDY #350

NEWARK #300

OC4 OCE OC7

NULL

Page 32: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

32

The ListNode Implementation (for AB Exam)

The previous example illustrates a Singly Linked List

This type of LinkedList contains a Head node and each node only knows about its next node

Page 33: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

33

A Singly Linked List is best used in cases where we insert new nodes in the beginning (not in the middle or the end) of the list and where searches in the list are minimized

Go to the handout that displays the ListNode class

For us to create our own LinkedList we need to create a “node” class

Page 34: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

34

This class must contain two class level attributes, one to hold an actual data element and one to hold the reference to the next node in the list

There are also methods to set these values

Page 35: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

35

public class ListNode{ private Object value; private ListNode next; public ListNode(Object initValue, ListNode initNext) { value = initValue; next = initNext; } public Object getValue() { return value; } public ListNode getNext() { return next; }

Page 36: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

36

public void setValue(Object theNewValue) { value = theNewValue; } public void setNext(ListNode theNewNext) { next = theNewNext; }

Page 37: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

37

This ListNode is self-referential as it refers to the ListNode data type inside the ListNode datatype

When we implement our own LinkedList we will use this class as our standard node class

The ListNode class, as currently constructed, reflects a Singly LinkedList

Page 38: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

38

Furthermore, the ListNode class is going to be used on the AP exam for questions on any LinkedList question

Also this class would be used as a base for any LinkedList Free Response question

What is missing from this class is the actual data that is to be maintained at each node

Page 39: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

39

The attribute private Object value; needs to hold some value

It can be ANY object, but we will use in our examples an object that maintains flight information

Page 40: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

40

public class AirFlight{

private String Destination;private int flightNum;

public AirFlight(String s, int num){

Destination = s;flightNum = num;

}

public String getDestination(){

return Destination;}

Page 41: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

41

public int getFlightNum()

{

return flightNum;

}

public String toString()

{

return Destination + " flight #" + flightNum;

}

}

Page 42: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

42

The flight class does not “KNOW” it is a part of a list and it only contains information about a specific airline flight

Page 43: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

43

The ListNode class does not care about the type of object at each node, it only cares about maintaining a REFERENCE to an object and the LOCATION of the next node

Page 44: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

44

This provides a level of abstraction

In the next sections we will examine the SampleLinkedList code to see a LinkedList in action

Page 45: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

45

ListNode as a Generic Class

As presently Constructed, the ListNode class accepts an Object reference as the “value” Being linked.

Therefore, when we GET the state of the value pointed to by a given Node, we must CAST to the specific object we are linking

Page 46: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

46

ListNode as a Generic Class

For Example, if we are linking instances of Airflight we must:

AirFlight a = (AirFlight)head.getValue();

However, if we were to modify the ListNode class to be Generic, we can set the “value”

Page 47: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

47

ListNode as a Generic Class

Object when the Node is constructed, then we would do the following:

ListNode<Integer> node = new ListNode<Integer>(12);

Then we do not need to cast when accessing the “value” at a given node:

Integer I = head.getValue()

Page 48: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

48

ListNode as a Generic Class

Furthermore, we must use the generic constructor whenever we create a Node instance:

head.setNext(new ListNode<Integer>(34));

Page 49: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

49

ListNode as a Generic Class

TestListNodeGeneric.java is the driver program that utilizes a generic ListNode class.

You will be writing the supporting ListNode class as one of your assignments.

Page 50: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

50

Linked List Behaviors:Like any other List Data Structure a

LinkedList must provide for the following behaviors:

Create a new list

Insert (Add) a new node to the list

Remove a node from the list

Traverse (Iterate) the nodes in the list

Page 51: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

51

To begin working with your own LinkedList (not java’s LinkedList class) you need to create a class that will hold the information you wish to store

You then need to Create an initial Node in the list and make this node the head of the list

Page 52: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

52

Lets work with our flight class and create an initial instance of it:

AirFlight f1 = new AirFlight("Atlanta", 100);Then create an initial node to maintain the

flight data:

ListNode node = new ListNode(f1, null); // A

Then establish this as the start of the list:

ListNode head = null;

head = node;

Page 53: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

53

We can now add or insert nodes to the front of the list

We can do this 2 ways, we can use the ListNodes setNext method to point the initial node to the next node in the list:

head.setNext(new ListNode(f2, null)); // A O

Page 54: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

54

Or we can use the ListNodes constructor to establish a new node and reset the head

head = new ListNode(f4,head);// N K A O

head = new ListNode(f5,head);// U N K A O

head = new ListNode(f6,head);// H U N K A O

Lets Draw out the resulting linked list on the Board…

Page 55: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

55

We can print out the contents of the first node:

System.out.println("The first Node is " + ((AirFlight)head.getValue()).toString());

Note that AirFlight class has a toString method

Page 56: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

56

We can also retrieve the object at the head node

AirFlight a = (AirFlight)head.getValue();

We can easily remove a node from the front of the list:

head = head.getNext();

Page 57: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

57

This remove works by setting the head to bypass the first node and point to the second node

Once the garbage collector sees that the first node is no longer referenced, it will destroy it

Page 58: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

58

We can traverse the list:

for (node = head2; node != null ; node = node.getNext())

{

b = (AirFlight)node.getValue();

System.out.println(b.toString());

}

Lets look at the sample code SampleLinkedList.java to see how to add and remove nodes from the end of the list

Page 59: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

59

Singly Linked ListA Singly LinkedList is one where the

nodes in the link know only about the node that FOLLOWS it

Head = OC4

OC4 OC7 OC1 BA3 CD4 AE4

Hou Utah New Ken Atl Orlando

OC7 OC1 BA3 CD4 AE4 NULL

Page 60: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

60

Insertion and removal at the beginning of the list are efficient as they are constant time O(1)

Searches and traversals are Linear time O(n)

Page 61: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

61

Linked List with a Tail

We keep track of the head node to provide us with the start of the list

We can also keep track of the last node of the list by maintaining a reference to its tail

Page 62: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

62

ListNode tail = head2;Then as we insert new nodes we update

the tail reference:

node = new ListNode(f2,null);

// change previous "tails" next node

// BEFORE updating the list to include the NEW tail

tail.setNext(node);

tail = node;

Page 63: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

63

Using the tail we can traverse from the end of the list and insert to the end of the list

In the previous example the head is still OC4 but the tail is AE4

Page 64: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

64

Circular Linked ListIn a circular linked list, we maintain the

reference to the head of the list in the last node of the list

This type of list does not contain a NULL next pointer in the last node to signify the end of the list

We know the list has been fully traversed when the “next” reference matches the head’s reference

Page 65: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

65

ListNode head3 = new ListNode(f1, null);

tail = head3;

tail.setNext(head3);

node = new ListNode(f2,null);

// change previous "tails" next node

// BEFORE updating the list to include the NEW // tail

tail.setNext(node);

tail = node;

tail.setNext(head3); // 8. Cir LL requires last // node's "next" to point to HEAD or First node

Page 66: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

66

Traversal of a Circular list is different as we can no longer check for NULL:

node = head3;do {

b = (AirFlight)node.getValue();System.out.println(b.toString());node = node.getNext();

System.out.println(node + " "+ head3);

}while (node != head3); // this is a circular // linked list !!!

Page 67: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

67

Doubly Linked List

A Doubly Linked list improves on the singly LinkedList because each node contains a reference to the node before it as well as the node after it

Before we can implement this type of List we need to enhance the ListNode class to add in a reference to the previous node:

Page 68: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

68

private ListNode prev;We also overload the constructor to

create a doubly Linked List

public ListNode(Object initValue, ListNode initNext, ListNode initPrev)

{

value = initValue;

next = initNext;

prev = initPrev; // DOUBLY LINKED LIST

Page 69: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

69

We also need to be able to access and modify the previous reference:

public ListNode getPrev()

{

return prev;

}

public void setPrev(ListNode theNewPrev)

{

prev = theNewPrev;

}

Page 70: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

70

A Doubly Linked List is used to maintain an ordered list of nodes

Our Insertion and Removal become more involved as we need to iterate through the nodes

For Insertions, we need to know if the node is the first one created

If it is then it is the head node and its NEXT and PREV references are null

Page 71: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

71

Otherwise, we traverse the list, keeping track of the prev node, until we locate a node whose data is greater than the data in the new node

Once the proper place is found we link the previous node to point to the new node

Then we have the new node point to the “previous” node’s next node

Page 72: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

72

We still have to maintain the prev references

The new node points back to the “previous” node and the node the new node points to needs have its prev node refer to the new node

Page 73: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

73

Lets put an example on the board (#5 in code handout)

Page 74: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

74

Lets look at the sample code for the Doubly Linked List example

Page 75: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

75

Sample Code Review

For a more complete review of a Linked List lets refer to the sample code : SampleLinkedList.java

Page 76: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

76

TPS Create Your Own Linked List

Make a copy of the following files to your student account:

LittleList.java TestMyList.java

These files are online as are the TPS instructions

You will create your own list class

Page 77: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

77

TPS2 Create a Templeted / Generic Version of the ListNode class

We can also Convert the ListNode class to utilize Generic Capability

In this case, we would modify the ListNode class to accept a specific object to be Linked

Page 78: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

78

TPS2 Create a Templeted / Generic Version of the ListNode class

The following is a code sample of the Driver program that utilizes a generic ListNode:

ListNode head = null;ListNode<Integer> node = new

ListNode<Integer>(12);head = node;System.out.println("The first Node is " +

(head.getValue()).toString());

Page 79: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

79

TPS2 Create a Templeted / Generic Version of the ListNode class

NOTE: the getValue method of ListNode’s Generic Version DOES NOT require a

Cast to a specific object, Integer, in this case.

// add a node to the list using the setnext method

// this will be the second node in the list

head.setNext(new ListNode<Integer>(34);

Page 80: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

80

TPS2Create a Templeted / Generic Version of the ListNode class

// add new nodes to the BEGINNING OF THE LIST

ListNode<Integer> t = new ListNode<Integer>(65);

t.setNext(head);

head = t;

System.out.println("The New first Node is " + (head.getValue()).toString());

Page 81: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

81

TPS2 Create a Templeted / Generic Version of the ListNode class

Now Traverse the List, Note: YOU CANT USE FOR EACH LOOP AS OUT LISTNODE DOES NOT UTILIZE ITERATOR OR LISTITERATOR

Integer b;for (node = head; node != null ; node =

node.getNext()){

b = node.getValue();System.out.println(b.toString());

}

Page 82: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

82

TPS2 Create a Templeted / Generic Version of the ListNode class

Removing a Node:head = head.getNext();

Page 83: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

83

TPS2 Create a Templeted / Generic Version of the ListNode class

Modify ListNode to allow Generics

Make a copy of the following files to your student account:

TestListNodeGeneric.java

Using this code as a guide, create your own version of a generic ListNode class

Page 84: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

84

Java’s LinkedList Class

Java has a LinkedList class that is designed to be a Doubly Linked List

This class is used in much the same way as the ArrayList class

Page 85: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

85

LinkedList ll = new LinkedList();

ll.add(f1);

ll.add(f2);

ll.remove(1); // removes

ll.removeLast();

System.out.println();

System.out.println("AFTER Removal There is NOW " + ll.size() + " Nodes in the List “);

printLL(ll);

AirFlight af = (AirFlight)ll.getFirst();

Page 86: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

86

You can loop thru a LinkedList by using the get(index) method, but it has hidden costs as we can explain by examining the following code:

for (int i = 0; i < ll.size(); i++)

{

AirFlight af = (AirFlight)ll.get(i);

}

Page 87: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

87

Each iteration begins AT THE START of the list and traverses to the i th node

You are responsible for understanding the implicit costs of the methods in the LinkedList class

Using the LinkedList class we can use the get method that returns the i th node

Page 88: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

88

Each call to this method traverses from the beginning of the list and has a Linear cost O(n)

We can move thru the list by iterative calls to the get method incrementing the index by one each time

However, EACH call to get STARTS at the HEAD node and becomes a Quadratic operation O(n^2)

Page 89: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

89

This leaves us with an efficiency issue that is addressed with the Iterator and ListIterator interfaces which we will discuss shortly

Lets open up and review Java’s LinkedList class in JavaDoc

Now Review the AP Subset for the LinkedList Class (USE AP JAVA DOC)

Page 90: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

90

It is important to note that there are some hidden performance issues to consider with the implementation of the List Interfaces get and set behaviors

The ArrayList implementation of these methods are an asset to the array as the “cost” of these operations is Constant --- O(1)

Page 91: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

91

The LinkedList implementation, however, is not as efficient

For a LinkedList to access the n th node it must start at the head of the list and traverse each node, counting each one, until it gets to the specified one --- Linear, O(n)

Page 92: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

92

In contrast the add behavior as implemented in a LinkedList merely rearranges the links while the ArrayList must rearrange its elements and/or copy them to a larger array

LinkedLists are also efficient at inserting a node at the beginning of the list or at the end (as long as it has a tail)

Page 93: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

93

Using the Generic Version of the LinkList Class

Java’s LinkedList Class is Generic, therefore, we can identify the type of Object we wish to link.

Code Examples are in the UseLinkedListClassWithGeneric.java file

Page 94: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

94

Using the AirFlight class as the object, we will create a LinkedList as follows:

LinkedList <AirFlight> ll = new LinkedList<AirFlight>();

AirFlight f1 = new AirFlight("Atlanta", 100);AirFlight f2 = new AirFlight("Orlando", 500);AirFlight f3 = new AirFlight("Kennedy",

350);ll.add(f1);ll.add(f2);ll.add(f3);

Page 95: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

95

Then you can Iterate using the FOR EACH loop:

for(AirFlight r:ll)

{

// display list with newark removed

System.out.println(r.toString());

}

Page 96: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

96

You can Iterate by calling a method and passing a LIST instance:

printLL(ll);static public void printLL( List ll )

{Iterator iter = ll.iterator();iter = ll.iterator();while(iter.hasNext()){// display list with newark removedSystem.out.println(iter.next());}

}

Page 97: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

97

You can Iterate by calling a method and passing a Generic LIST instance:

static public void printLLITERATOR( List<AirFlight> ll ){ for(AirFlight r:ll)

{// display list with newark removedSystem.out.println(r.toString());}

System.out.println(" AND TRAVERSE WITH AN ITERATOR...");

// NOW ITERATE using an iterator for(Iterator<AirFlight> itr = ll.iterator(); itr.hasNext();) { System.out.println(itr.next()); }

}

Page 98: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

98

Iterator InterfaceWe can traverse thru a list efficiently if we

have access to the first node in the list

for (node = head2; node != null ; node = node.getNext())

However, if we implement the linkedlist as part of an encapsulated class we do not have access to the head of the list

Page 99: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

99

We can use an Iterator to process thru a linkedlist

This gives us the flexibility to handle each node as we need to

We can make use of the Iterator to sequence through a list

The LinkedList class has an Iterator reference that can be used to “iterate” thru the list

Page 100: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

100

When you create an Iterator it points to a specific element in the list (usually the first node)

You can have multiple iterators against a single List object and each can be at a different “node”

Page 101: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

101

Iterating thru a Linked List

static public void printLL(List ll){

System.out.println();// instance of iteratorIterator iter = ll.iterator();// roll thru nodes of list until none are leftwhile(iter.hasNext())

{// returns the next node's Object (value) in the listSystem.out.println(iter.next());}

}

Page 102: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

102

Remove a node thru the iteratorwhile(iter.hasNext())

{// returns the next node's Object (value) in the // listAirFlight f = (AirFlight)iter.next();// remove the flight number 300 -- Newarkif (f.getFlightNum() == 300)

{ iter.remove(); System.out.println(f + " Removed");}

}

Page 103: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

103

ListIterator InterfaceIterators have limitations as they always

start at the beginning of the list and then only move forward (in one direction)

What if we had to find duplicate flights in a list of AirFlights

We could nest separate iterators but this is inefficient because the inner iterator will start at the first node each iteration

Page 104: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

104

AirFlight fl1, fl2;Iterator iter1, iter2;iter1 = ll.Iterator();while (iter1.hasNext( )){

fl1 = (AirFlight)iter1.next();iter2 = ll.Iterator(); // will start at first node each timewhile(iter2.hasNext( )){

fl2 = (AirFlight)iter2.next();

if (fl1 != fl2 && fl1.getFlightNum( ) == fl2.getFlightNum( ) )

System.out.println(“Duplicate Flight: “ + fl1.toString())}

}

Page 105: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

105

NOTE: The check fl1 != fl2 makes sure we are not comparing the same 2 flights

Java’s enhanced version of the Iterator is the ListIterator (java.util.ListIterator)

ListIterator EXTENDS the Iterator interface

Page 106: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

106

In the Full Java version of the ListInterface there are several methods that allow us to move forward as well as backward in the LinkedList (remember that the Java LinkedList is implemented as a Doubly LL)

To get the full power of this interface, look at the FULL Java Doc where the List Interface has an overloaded ListIterator that passes in an index so we can START our iteration at any point in the list

Page 107: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

107

Lets open up and review Java’s FULL VERSION OF THE Iterator & ListIterator Interfaces in JavaDoc

Therefore we can make our duplicate flight search more efficient:

Page 108: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

108

AirFlight fl1, fl2;ListIterator iter1, iter2;iter1 = ll.ListIterator();while (iter1.hasNext( )){

fl1 = (AirFlight)iter1.next();iter2 = ll.ListIterator(iter1.nextIndex( )); // will start at //index node each timewhile(iter2.hasNext( )){

fl2 = (AirFlight)iter2.next();if (fl1 != fl2 && fl1.getFlightNum( ) ==

fl2.getFlightNum( ) )System.out.println(“Duplicate Flight: “ +

fl1.toString())}

}

Page 109: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

109

Lets open up and review AP Java’s Iterator & ListIterator Interfaces in the AP JavaDoc (USE AP JAVA DOC)

Review the AP Subset for the Iterator and ListIterator Interfaces

Note that the AP subset for the List Interface DOES NOT include the overloaded ListIterator method

Page 110: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

110

add inserts a new node (specified element) into the list BEFORE the current iterator position and moves the iterator PAST the inserted element (node)

set replaces the value of the node (element) returned by the next method

remove method removes the last node returned by the iterator AND CAN only be called ONCE AFTER a call to the next method

Page 111: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

111

Lets look at the ListIterator sample code handout (JESG p.266-268)

For the AP exam we will not be asked to iterate through the LinkedList class as a doubly linked list as the AP version of the ListIterator class has limited behaviors

Page 112: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

112

Big-O of a Linked ListSingly Doubly LL CLass

Insert / Add /remove

to beginning of list O(1) O(1) O(1)

Insert / Add /Remove

to end of list O(n) O(1) O(1)

Insert / Remove in

(middle) of list O(n) for search O(n) for search O(n) for srch

O(1) for insert O(1) for insert O(1) for insert

Search for a key O(n) O(n) O(n)

Page 113: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

113

LinkedList Class

(Doubly LL)

addFirst, addLast,

getFirst, getLast,

removeFirst,

removeLast O(1)

set O(n) to locate note

Page 114: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

114

Examine the addlast code in Barrons page 248 and Determine its efficiency

Page 115: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

115

AP AB Subset Requirements

Students are expected to write linked list insert (add) to front, insert to tail, insert in order, remove, traverse, a singly, doubly or circular linked list

Students are also responsible for using the Java LinkedList class an the Iterator and ListIterator Interfaces

Page 116: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

116

Multiple Choice and Free Response Questions will use the ListNode class as the NODE for Linked List implementations

Students also need to understand the Big-O of Linked List behaviors and compare them to ArrayLists

Page 117: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

117

Students must also evaluate appropriate selection of a list (linked or array)

Page 118: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

118

LABS:

POE Revisited

Case Study Modifications

Barrons M/C Questions

Free Response Questions

Enhance the ListNode Class to implement a Doubly LL &

LL with Tail]

Handout of Multiple Choice Questions

Page 119: 1 Linked Lists Starring: Singly Linked List ListNode Doubly Linked List Iterator Co-Starring: ListIterator

119

TEST IS DAY AFTER THE

LABS ARE DUE !!!!!