CSCI1933 Lecture8
CSCI1933 Lecture8
- Comparison of implementations
Brief review of key concepts covered last time
Merge Sort
• Divide an array into halves
Sort the two halves
Merge them into one sorted array
- Comparison of implementations
Abstract data types and data
structures
Quick review of where we’ve been/where we’re
going
• Essentials of Java programming
• Basics of object-oriented programming
– Modular design
– Encapsulation
– Inheritance
• Now: we want to start applying these concepts to
solve useful and general problems
• One useful problem that shows up everywhere: how
do we efficiently/robustly manage large collections
of data (e.g. student records, user accounts, internet
traffic, genome data, …)
Motivation for data structure design
Rual et al. Towards a proteome-scale map of the human protein–protein interaction network. Nature 437, 1173-1178 (20 October 2005)
A simpler type of data: my weekend to-do list
- Comparison of implementations
Array-based implementation of list
data structure
• What member variables will we need?
– array to keep references to object in list
– integer to keep track of current size
– integer to keep track of max size
– ??
• Methods? (need to follow specifications)
public void add(T newEntry) // add to end of list
public T remove(int position) // remove a specific item
public int getLength() // return number of elements in list
Start of an Array List implementation
/**
A class that implements a list of objects by using an array.
Entries in a list have positions that begin with 1.
Duplicate entries are allowed. */
public AList()
{
this(DEFAULT_CAPACITY);
} // end default constructor
Implementation of some simple
methods
}
Implementing add method
Task: Adds newEntry to the end of the list.
Input: newEntry is an object.
Output: None.
if(numberOfEntries == list.length) {
// Error--list full!! Report or handle here
}
else {
list[numberOfEntries + 1] = newEntry;
numberOfEntries++;
}
} // end add
How about this version of add?
public boolean add(int newPosition, int newEntry)
Solution:
• We need to move everything to the right of the requested
position back by one position in the array
• How about we write a helper method called makeRoom?
Exercise: Implementing
makeRoom helper method
Data members:
list
numberofEntries
}
Exercise: Implementing
makeRoom helper method
} // end add
mylist.remove(2)
mylist.remove(2)
Note: we
need the
opposite of
“makeRoom”
method
here
removeGap
Carrano and Henry, Data Structures and Abstractions with Java.
remove method implementation
public T remove(int givenPosition)
{
checkIntegrity();
if ((givenPosition >= 1) && (givenPosition <= numberOfEntries))
{
Example:
List<String> stringList = new ArrayList<String>();
stringList.add(0,"string1")
stringList.add(1,"string2")
Overview of today’s material
- Comparison of implementations
Linked lists
An alternative list implementation: the linked list
Linked list:
• List is organized by keeping track of start (or end) only
• Each element of the list knows about the next element in the list
Waiting room analogy
First
patient
“urgent”
patient
Patient after
Patient before
Patient after
}
What type of structure/variable will we
need to store elements of a linked list?
• Requirements?
• should keep track of our data!
(e.g. patient info, illness, etc.)
• needs to store a reference to
the next patient
The Node Class
• An inner class that will contain a single element in
our list
– Inner class: a class defined within another class definition
• Nodes linked together + the methods will form our
linked list data structure
• Two data fields:
– A reference to an entry in the list
– A reference to another node
public LList()
{
clear();
} // end default constructor
// everything else…
public int getLength(){ return length; }
}
Adding elements to a linked list
• First, remember back to array
implementation:
if(numberOfEntries == list.length) {
// Error--list full!! Report or handle here
}
else {
list[numberOfEntries + 1] = newEntry;
numberOfEntries++;
}
} // end add
Adding elements to a linked list
• Now, how about the linked list?
First, let’s start by thinking of the possible starting states for the
list...
Adding elements to a linked list
• Possible cases:
– adding element to an empty list
– adding element to a list with existing
elements
Adding to the End of the List
(empty case)
if (isEmpty()) {
} // end if
length++;
return true;
} // end add
Adding elements to a linked list
public boolean add(T newEntry)
{
Node newNode = new Node(newEntry);
if (isEmpty())
firstNode = newNode;
else // add to end of nonempty list
{
Node lastNode = getNodeAt(length);
} // end if
length++;
return true;
} // end add
Adding to the End of the List (non-
empty case)
if (isEmpty())
firstNode = newNode;
else // add to end of nonempty list
{
Node lastNode = getNodeAt(length);
} // end if
length++;
return true;
} // end add
Exercise: We used a helper function getNodeAt
– how do we implement this?
public class LList<T> implements ListInterface<T>
{
private Node firstNode; // reference to first node
private int length; // number of entries in list
?
}
}
Exercise: We used a helper function getNodeAt
– how do we implement this?
public class LList<T> implements ListInterface<T>
{
private Node firstNode; // reference to first node
private int length; // number of entries in list
currentNode=firstNode;
for(int counter=1; counter < givenPosition; counter++) {
currentNode = currentNode.next;
}
}
return currentNode;
}
}
Now, how about adding elements in
the middle of a linked list?
public boolean add(int newPosition, T newEntry)
Error conditions?
Case 1: adding at Beginning of the List
• add(T)
• add(i, T)
• clear(), getLength(), isEmpty()
• remove(i)
• replace(i,T)
• getEntry(i)
• contains(T)
Removing an element from a linked list
public T remove(int givenPosition)
(see Carrano and Henry, Chapter 12, for details on linked list implementation)
Overview of today’s material
- Comparison of implementations
Comparison of array and linked list List
implementations
• Which is better?
– Memory?
– Speed?
• Which is better?
– Memory?
• Array List: wastes memory for each unfilled
slot in the array
• Linked List: only create one node per element,
BUT requires memory overhead of links
Comparison of array and linked list List
implementations
• Which is better?
Assume N elements– what’s the number of operations in the worst case?
– Speed?
• getEntry (int position)
• Array List: ?
• Linked List: ?
– Speed?
• getEntry (int position)
• Array List: O(1) (doesn’t depend on the size of the
array)
• Linked List: requires traversal of all preceding elements
(worst-case: last element, complexity ~ O(N))
Comparison of array and linked list List
implementations
• Which is better?
Assume N elements– what’s the number of operations in the worst case?
– Speed?
• remove(int position)
• Array List: ?
• Linked List: ?
– Speed?
• remove(int position)
• Array List: needs reshuffling (worst case: first
element, complexity ~ O(N))
• Linked List: simply “rewire” links in constant time,
but we still need to find this element (worst case:
last element, complexity ~O(N))
Summary of Pros and Cons of a linked list
implementation
• The linked list can grow as large as necessary
• Can add and remove nodes without shifting existing
entries
But …
• Must traverse a chain to determine where to make
addition/deletion
• Retrieving an entry requires traversal
– As opposed to direct access in an array
• Requires more memory for links
– But does not waste memory for oversized array
Variations on the linked list
• Also include a tail reference (reference to the
last node of the list) Why?
if (isEmpty())
firstNode = newNode;
else // add to end of nonempty list
{
Node lastNode = getNodeAt(length);
} // end if
length++;
return true;
} // end add
getNodeAt method
currentNode=firstNode;
for(int counter=1; counter < givenPosition; counter++) {
currentNode = currentNode.next;
}
}
return currentNode;
}
}
Updated LList data member– lastNode
...
}
Adding elements to a linked list
public boolean add(T newEntry)
{
Node newNode = new Node(newEntry);
if (isEmpty())
firstNode = newNode;
else // add to end of nonempty list
{
Node lastNode = getNodeAt(length);
} // end if
if (isEmpty())
firstNode = newNode;
else // add to end of nonempty list
{
lastNode.next = newNode;
lastNode = newNode;
} // end if
length++;
return true;
} // end add
Java Class Library: The Class LinkedList