2/20/2012
1
Linked Lists
slides created by Marty Stepphttp://www.cs.washington.edu/143/
Modified by Sarah Heckman
Reading: RS Chapter 16
2
References and objects• In Java, objects and arrays use reference semantics. Why?
– efficiency. Copying large objects slows down a program.– sharing. It's useful to share an object's data among methods.
DrawingPanel panel1 = new DrawingPanel(80, 50);DrawingPanel panel2 = panel1; // same windowpanel2.setBackground(Color.CYAN);
panel1
panel2
2/20/2012
2
3
References as fields• Objects can store references to other objects as fields.
– HtmlValidator stores a reference to a Queue– the Queue stores many references to HtmlTag objects– each HtmlTag object stores a reference to its element String
private Queue<HtmlTag> queue;...
HtmlValidator
back.........frontQueue
private String element;...
HtmlTag
private String element;...
HtmlTag
lmthString ydobString
4
Null references•null : A value that does not refer to any object.
– Unset reference fields of an object are initialized to null.
public class Student {String name;int id;
}
Student timmy = new Student();
name null
timmy id 0
2/20/2012
3
5
Things you can do w/ null• store null in a variable or an array element
String s = null;words[2] = null;
• print a null referenceSystem.out.println(timmy.name); // null
• ask whether a variable or array element is nullif (timmy.name == null) { ... // true
• pass null as a parameter to a method– some methods don't like null parameters and throw exceptions
• return null from a method (often to indicate failure)return null;
6
Dereferencing• dereference: To access data or methods of an object.
– Done with the dot notation, such as s.length()– When you use a . after an object variable, Java goes to the
memory for that object and looks up the field/method requested.
Student timmy = new Student();timmy.name = "Timmah";String s = timmy.name.toUpperCase();
name nulltimmy
id 0
'T' 'i' 'm' 'm' 'a' 'h'
Student String
public int indexOf(String s) {...}public int length() {...}public String toUpperCase() {...}
2/20/2012
4
7
Null pointer exception• It is illegal to dereference null (it causes an exception).
– null does not refer to any object, so it has no methods or data.
Student timmy = new Student();String s = timmy.name.toUpperCase(); // ERROR
Output:Exception in thread "main"java.lang.NullPointerException
at Example.main(Example.java:8)
name nulltimmy
id 0
8
References to same type• What would happen if we had a class that declared one of its
own type as a field?
public class Strange {private String name;private Strange other;
}
– Will this compile?• If so, what is the behavior of the other field? What can it do?• If not, why not? What is the error and the reasoning behind it?
2/20/2012
5
9
Linked data structures• All of the collections we will use and implement in this course
use one of the following two underlying data structures:
– an array of all elements•ArrayList, Stack, HashSet, HashMap
– a set of linked objects, each storing one element,and one or more reference(s) to other element(s)•LinkedList, TreeSet, TreeMap
42 -3 17 9
front 42 -3 17 9 null
10
A list node classpublic class ListNode {
int data;ListNode next;
}
• Each list node object stores:– one piece of integer data– a reference to another list node
•ListNodes can be "linked" into chains to store a list of values:
data next42
data next-3
data next17
data next9 null
2/20/2012
6
11
List node client examplepublic class ConstructList1 {
public static void main(String[] args) {ListNode list = new ListNode();list.data = 42;list.next = new ListNode();list.next.data = -3;list.next.next = new ListNode();list.next.next.data = 17;list.next.next.next = null;System.out.println(list.data + " " + list.next.data
+ " " + list.next.next.data);// 42 -3 17
}}
data next42
data next-3
data next17 nulllist
12
List node w/ constructorpublic class ListNode {
int data;ListNode next;
public ListNode(int data) {this.data = data;this.next = null;
}
public ListNode(int data, ListNode next) {this.data = data;this.next = next;
}}
2/20/2012
7
13
References vs. objectsvariable = value;
a variable (left side of = ) is an arrow (the base of an arrow)
a value (right side of = ) is an object (a box; what an arrow points at)
• For the list at right:
– a.next = value;means to adjust where points
– variable = a.next;means to make variable point at
data next10
a data next
201
2
1
2
14
Reassigning references• when you say:
– a.next = b.next;
• you are saying:– "Make the variable a.next refer to the same value as b.next."– Or, "Make a.next point to the same place that b.next points."
data next10
a data next
20
data next30
b data next
40
2/20/2012
8
15
Linked Node Questiondata next10
data next30
list data next
20
data next40
data next60
temp data next
50
data next10
data next30
list data next
20
data next40
data next60
Before
After
16
Linked node question• Suppose we have a long chain of list nodes:
– We don't know exactly how long the chain is.
• How would we print the data values in all the nodes?
data next10
data next990
list...
data next
20
2/20/2012
9
17
Algorithm pseudocode• Start at the front of the list.• While (there are more nodes to print):
– Print the current node's data.– Go to the next node.
• How do we walk through the nodes of the list?
list = list.next; // is this a good idea?
data next10
data next990
list...
data next
20
18
Traversing a list?• One (bad) way to print every value in the list:
while (list != null) {System.out.println(list.data);list = list.next; // move to next node
}
– What's wrong with this approach?
data next10
data next990
list...
data next
20
2/20/2012
10
19
A current reference• Don't change list. Make another variable, and change that.
– A ListNode variable is NOT a ListNode object
ListNode current = list;
• What happens to the picture above when we write:
current = current.next;
data next10
data next990
list...
data next
20
current
20
Traversing a list correctly• The correct way to print every value in the list:
ListNode current = list;while (current != null) {
System.out.println(current.data);current = current.next; // move to next node
}
– Changing current does not damage the list.
data next10
data next990
list...
data next
20
2/20/2012
11
21
Linked list vs. array• Algorithm to print list values:
ListNode front = ...;
ListNode current = front;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
• Similar to array code:
int[] a = ...;
int i = 0;
while (i < a.length) {
System.out.println(a[i]);
i++;
}
22
A LinkedIntList class• Let's write a collection class named LinkedIntList.
– Has the same methods as ArrayIntList:•add, add, get, indexOf, remove, size, toString
– The list is internally implemented as a chain of linked nodes• The LinkedIntList keeps a reference to its front as a field•null is the end of the list; a null front signifies an empty list
front
sizeadd(value)add(index, value)indexOf(value)remove(index)size()toString()
LinkedIntListListNode ListNode ListNode
data next42
data next
-3data next
17
element 0 element 1 element 2
2/20/2012
12
23
LinkedIntList class v1public class LinkedIntList {
private ListNode front;private int size;
public LinkedIntList() {front = null;size = 0;
}
methods go here
}
front =
size = 0
LinkedIntList
24
Implementing add// Adds the given value to the end of the list.public void add(int value) {
...}
– How do we add a new node to the end of a list?– Does it matter what the list's contents are before the add?
front =
size = 3
data next42
data next
-3data next
17
element 0 element 1 element 2
2/20/2012
13
25
Adding to an empty list• Before adding 20: After:
– We must create a new node and attach it as the front of the list.
front =
size = 0
front =
size = 1
data next20
element 0
26
The add method, 1st try// Adds the given value to the end of the list.public void add(int value) {
if (front == null) {// adding to an empty listfront = new ListNode(value);
} else {// adding to the end of an existing list
...
}}
2/20/2012
14
27
Adding to non-empty list• Before adding value 20 to end of list:
• After:
front =
size = 2
data next42
data next-3
front =
size = 3
data next42
data next-3
data next
20
element 0 element 1 element 2
element 0 element 1
28
Don't fall off the edge!• To add/remove from a list, you must modify the next
reference of the node before the place you want to change.
– Where should current be pointing, to add 20 at the end?– What loop test will stop us at this place in the list?
front =
size = 2
data next42
data next-3
element 0 element 1
2/20/2012
15
29
The add method// Adds the given value to the end of the list.public void add(int value) {
if (front == null) {// adding to an empty listfront = new ListNode(value);
} else {// adding to the end of an existing listListNode current = front;while (current.next != null) {
current = current.next;}current.next = new ListNode(value);
}size++;
}
30
Implementing add (2)// Inserts the given value at the given index.public void add(int index, int value) {
...}
front =
size = 3
data next42
data next
-3data next
17
element 0 element 1 element 2
2/20/2012
16
32
Conceptual questions• What is the difference between a LinkedIntList and a ListNode?
• What is the difference between an empty list and a null list?– How do you create each one?
• Why are the fields of ListNode public? Is this bad style?
• What effect does this code have on a LinkedIntList?
ListNode current = front;current = null;
34
Implementing remove// Removes value at given index from list.public void remove(int index) {
...}
– How do we remove any node from a list?– Does it matter what the list's contents are before the remove?
front =
size = 3
data next42
data next
-3data next
20
element 0 element 1 element 2
2/20/2012
17
35
Removing from a list• Before removing element at index 1:
• After:
front =
size = 2
data next42
data next
20
front =
size = 3
data next42
data next
-3data next
20
element 0 element 1 element 2
element 0 element 1
36
Removing from the front• Before removing element at index 0:
• After:
front =
size = 2
data next-3
data next
20
front =
size = 3
data next42
data next
-3data next
20
element 0 element 1 element 2
element 0 element 1
2/20/2012
18
37
Removing the only element• Before: After:
– We must change the front field to store null instead of a node.– Do we need a special case to handle this?
front =
size = 0
front =
size = 1
data next20
element 0
38
remove solution// Removes value at given index from list.// Precondition: 0 <= index < size()public void remove(int index) {
if (index == 0) {// special case: removing first elementfront = front.next;
} else {// removing from elsewhere in the listListNode current = front;for (int i = 0; i < index - 1; i++) {
current = current.next;}current.next = current.next.next;
}size--;
}
2/20/2012
19
39
Exercise• Write pseudocode for addSorted that accepts an integer
value as a parameter and adds that value to a sorted list in sorted order.
– Before addSorted(17) :
– After addSorted(17) :
front =
size = 3
data next-4
data next
8data next
22
element 0 element 1 element 2
front =
size = 4
data next-4
data next
17data next
22
element 0 element 2 element 3
data next
8
element 1
40
The common case• Adding to the middle of a list:
addSorted(17)
– Which references must be changed?– What sort of loop do we need?– When should the loop stop?
front = data next-4
data next
8data next
22
element 0 element 1 element 2
2/20/2012
20
41
First attempt• An incorrect loop:
ListNode current = front;while (current.data < value) {
current = current.next;}
• What is wrong with this code?– The loop stops too late to affect the list in the right way.
front = data next-4
data next
8data next
22
element 0 element 1 element 2
current
42
Key idea: peeking ahead• Corrected version of the loop:
ListNode current = front;while (current.next.data < value) {
current = current.next;}
– This time the loop stops in the right place.
front = data next-4
data next
8data next
22
element 0 element 1 element 2
current
2/20/2012
21
43
Another case to handle• Adding to the end of a list:
addSorted(42)
Exception in thread "main": java.lang.NullPointerException
– Why does our code crash?– What can we change to fix this case?
front = data next-4
data next
8data next
22
element 0 element 1 element 2
45
Third case to handle• Adding to the front of a list:
addSorted(-10)
– What will our code do in this case?– What can we change to fix it?
front = data next-4
data next
8data next
22
element 0 element 1 element 2
2/20/2012
22
46
Handling the front• Another correction to our code:
if (value <= front.data) {// insert at front of listfront = new ListNode(value, front);
} else {// insert in middle of listListNode current = front;while (current.next != null &&
current.next.data < value) {current = current.next;
}}
– Does our code now handle every possible case?
47
Fourth case to handle• Adding to (the front of) an empty list:
addSorted(42)
– What will our code do in this case?– What can we change to fix it?
front =
2/20/2012
23
48
Final version of code// Adds given value to list in sorted order.// Precondition: Existing elements are sortedpublic void addSorted(int value) {
if (front == null || value <= front.data) {// insert at front of listfront = new ListNode(value, front);
} else {// insert in middle of listListNode current = front;while (current.next != null &&
current.next.data < value) {current = current.next;
}}
}
49
Linked vs. array lists• We have implemented the following two collection classes:
– ArrayIntList
– LinkedIntList
– They have similar behavior.We should be able to treat them the same way in client code.
index 0 1 2 3value 42 -3 17 9
front
data next42
data next
-3data next
17data next
9
2/20/2012
24
50
An IntList interface// Represents a list of integers.public interface IntList {
public void add(int value);public void add(int index, int value);public int get(int index);public int indexOf(int value);public boolean isEmpty();public void remove(int index);public void set(int index, int value);public int size();
}
public class ArrayIntList implements IntList { ...public class LinkedIntList implements IntList { ...
Top Related