* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download linked list
Survey
Document related concepts
Transcript
CSE 501N
Fall ‘09
10: Introduction to Collections and Linked
Lists
29 September 2009
Nick Leidenfrost
Lecture Outline
Data Structures
Linked List
Iterators
2
Arrays
The shortcomings
Fixed size
Insertion into the middle of a contiguous
array
Removal from the middle of a contiguous
array
3
Data Structures
Objects whose purpose is to organize data
(primitives or other objects)
Allow us to store large amounts of information
when it is not desirable to do so with an array
Can grow and shrink as needed
Can be more efficient to search than arrays in
certain cases
4
Data Structures
Java Libraries
Java provides several data structures in its
libraries
Contained
in the java.util package
[ To the JavaDoc, Batman! ]
In the next few weeks we will be exploring
some of these Data Structures and
learning their strengths and weaknesses
When
it is appropriate to use a particular
structure
5
Linked Lists
One of the most basic data structures is the
linked list
A linked list is a data structure which consists of
a number of nodes, each of which has some
contents and a reference to the next node
List
Node
Node
Node
Node
(storage)
(storage)
(storage)
(storage)
6
Linked Lists
Code View
A linked list is a data structure which consists of a
number of nodes (instances of a Node class), each
of which has some contents (instance variable) a
reference to the next node (instance variable)
class SinglyLinkedList
Node head;
class Node
Object storage;
Node next;
Object storage;
Node next;
Object storage;
Node next;
7
Linked Lists vs. Arrays
Adding and removing elements in the middle of
a linked list is efficient
Visiting the elements of a linked list in sequential
order is efficient
Random access is not efficient
Lists can grow arbitrarily large
(Resizing
is efficient)
8
Linked Lists
Implementation
To keep it simple, we will look at
implementing a singly-linked list
“Singly Linked” because Nodes only
know about the Node after them (References,
or links only go in one direction)
You will be asked to implement a Doubly
Linked List in Lab 4
Called
9
Linked Lists
Implementation
Node class
a reference to the next Node
Holds a reference to the Object it is storing
Holds
SinglyLinkedList class
Holds
a reference head to the first node
List
Node
Node
Node
Node
(storage)
(storage)
(storage)
(storage)
10
Lists
In Code
public class Node {
Object contents;
Node nextNode;
}
public Node (Object contents) {
this.contents = contents;
}
public class SinglyLinkedList {
Node head;
public SinglyLinkedList () {
this.head = null;
}
}
11
Adding a New First Element
When a new Node is added to the list
It
becomes the head of the list
The old list head becomes its next Node
public class SinglyLinkedList {
// . . .
public void addFirst (Object add) {
Node newNode = new Node(add);
newNode.next = this.head;
this.head = newNode;
}
}
12
Removing the First Element
When the first element is removed
The
data of the first node are saved and later
returned as the method result
The successor of the list head becomes the
list head
The old node will be garbage collected when
there are no further references to it
13
Removing the First Element
The removeFirst method
public class SinglyLinkedList {
// . . .
public Object removeFirst() {
if (head == null)
return null;
Object obj = this.head.contents;
this.head = this.head.next;
return obj;
}
}
14
Getting an Element by Index
The getNth method
public Object getNth (int index) {
Node search = this.head;
for (int i=0; i<index; i++) {
if (search == null)
return null;
search = search.next;
}
return search.contents;
}
15
Iterating Over Data Structures
Iterating over a Linked List
We
could just use a regular for loop:
for (int i=0; i<list.getSize(); i++) {
Object nth = list.getNth(i);
... // Do something with ‘nth’
}
But what is this doing internally?
[ Example on Board ]
Very
inefficient
16
Iterators
Helpers for Stepping through Data Structures
Let’s define a way for users to iterate
through our data structure
(SinglyLinkedList), one element at a time
Internal
Iterator
[ Example on Board ]
But what if multiple different entities want
to iterate over the Data Structure?
Position
is invalidated for other users
17
Iterators
Safely Exporting State
What we need is a way to encapsulate
(package up) and export a position in the
Data Structure…
Allow
multiple different simultaneous iterators
over the Data Structure
We need to have a trusted way of providing a
reference to our internal representation
Exporting our internal representation
How is this done?
18
Levels of Encapsulation
Exporting State Safely
We want the internal structure (Nodes) of the
linked list to be as protected as possible
We want to be able to export some notion of a
position within the list
The
easiest way to do this would be a reference to a
Node
But we don’t want to expose the Node object
itself
Write
an encapsulation for the behavior we want to
export
19
Packages and Access Modifiers
Classes that Work Together Closely
Put our SinglyLinkedList, our Node, and
our ListIterator classes inside of package
Declare Node head in SinglyLinkedList
with the protected access modifier
ListIterator can access protected fields of
the List, because List and ListIterator are
in the same package
Make the constructor of ListIterator
protected so that it must be created via the
SinglyLinkedList
20
Iterators
ListIterator type
Gives
access to elements inside a linked list
Encapsulates the concept of a ‘position’
anywhere inside the linked list
Protects the internal structure of the linked list
while giving access
22
A List Iterator
23
List Iterator
Think of an iterator as pointing between two elements
in a data structure
Analogy: like the cursor in a word processor points
between two characters
The iterator method of the SinglyLinkedList
class gets a new ListIterator
Points to the beginning of the list
SinglyLinkedList employeeNames = new SinglyLinkedList();
ListIterator iterator = employeeNames.iterator();
24
A Conceptual View of a List Iterator
25
List Iterator
Initially, the iterator points before the first
element
hasNext returns true if there is a next
element
if (iterator.hasNext())
iterator.next();
The next method moves the iterator and
returns the current item
Object next = iterator.next();
26
List Iterator
The next method returns the element that
the iterator is passing
while (iterator.hasNext()) {
Object obj = iterator.next();
// Do something with obj
}
27
LinkedListIterator
The LinkListIterator class
package listutil;
public class LinkedListIterator {
Node previous, position;
List list;
public LinkedListIterator(List list) {
this.list = list;
this.position = null;
this.previous = null;
}
}
}
28
Linked List Iterator
hasNext Method
The next method should only be called
when the iterator is not at the end of the
list
If
hasNext returns true
The iterator is at the end if…
the
list is empty (list.head == null)
there
is no element after the current position
(position.next == null)
29
The Linked List Iterator
hasNext Method
private class LinkedListIterator {
//. . .
public boolean hasNext() {
if (position == null)
return (list.head != null);
else return (position.next != null);
}
//. . .
}
30
The Linked List Iterator
next Method
position: reference to the last visited Node
previous: reference to the Node before
position
next method: position reference is
advanced to position.next
Last position is remembered in previous
If the iterator points before the first element
of the list, then the previous is null
and position must be set to list.head
31
The Linked List Iterator
next Method
public Object next() {
if (!hasNext())
return null;
previous = position; // Remember for remove
if (position == null)
position = list.head;
else position = position.next;
return position.contents;
}
32
The Linked List Iterator
remove Method
If the element to be removed is the first
element, call list.removeFirst
Otherwise, the node preceding the
element to be removed needs to have its
next reference updated to skip the
removed element
33
The Linked List Iterator
remove Method
public void remove() {
if (previous == position)
return; // Invalid state!
if (position == list.head) {
list.removeFirst();
}
else {
previous.next = position.next;
}
position = previous;
}
34
Removing a Node From the Middle of
a Linked List
35
The Linked List Iterator
remove Method: Caveats
If the previous equals position:
Then the call to remove does not immediately follow
a call to next
Method cannot execute properly
(throw an IllegalArgumentException)
is illegal to call remove twice in a row
remove sets the previous reference to position
It
36
The Linked List Iterator
set Method
Changes the data stored in the previously
visited element
The set method
public Object set (Object obj) {
Object contents = null;
if (position != null) {
contents = position.contents;
position.contents = obj;
}
return contents;
}
37
The Linked List Iterator
add Method
add inserts the new node after the
current position
The most complex operation is the
addition of a node
Sets the successor of the new node to the
successor of the current position
38
The Linked List Iterator's
add Method
public void add(Object obj) {
if (position == null) {
list.addFirst(obj);
position = list.head;
previous = null;
}
else {
Node newNode = new Node(obj);
newNode.next = position.next;
position.next = newNode;
previous = position;
position = newNode;
}
}
39
Adding a Node to the Middle of
a Linked List
40
Conclusion
Lab 3 assigned today
Arrays
& Iteration
Lab 2 due by midnight
I will be in lab now
41