Last time:
* Linked structures
* singleended list
Today:
* Doubleended list
* doublylinked list
* The "containerofreferences" model
* Intro to templates
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
What if we wanted to insert something at the end of the list?
Intuitively, with the current representation, we'd need to walk down
the list until we found "the last element", and then insert it there.
That's not very efficient, because we'd have to examine every element
to insert anything at the tail.
Instead, we'll change our concrete
representation to track both the front and the back of our list.
The
new rep has *two* node pointers:
class IntList {
node *first;
node *last;
public:
...
};
The invariant on first is unchanged.
The invariant on "last" is:
last points to the last node of the list if it is not empty, and is
NULL otherwise.
So, in an empty list, both data members point to NULL.
However, if
the list is nonempty, they look like this:
++
++
++
++
first>  >  >  >  \
++
++
++
++
\
^

last/

Note: adding this new data member requires that *every* method (except
isEmpty) be rewritten.
In lecture, we'll only rewrite insertLast.
First, we create the new node, and establish its invariants:
void IntList::insertLast(int v)
{
node *np = new node;
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
np>value = v;
...
}
To actually insert, there are two casesif the list is empty, we
need to reestablish the invariants on first *and* lastthe new node
is both the first and last node of the list. If the list is *not*
empty, there are still two broken invariants.
The "old" last element
(incorrectly) points to NULL, and the "last" field no longer points to
the last element.
void IntList::insertLast(int v)
{
node *np = new node;
np>next = NULL;
np>value = v;
if (isEmpty()) {
first = np;
} else {
last>next = np;
}
last = np;
}
Now how many pointers must be examined?
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
This is efficient, but only for insertion.
To make removal from the end efficient, as well, we have to have a
doublylinked list, so we can go forward *and* backward from any
inidivdual node.
To do this, we're going to change the representation
yet again.
In our new representation, a node is:
struct node {
node *next;
node *prev;
int
value;
}
The next and value fields are the same.
The "prev" field's invariant
is:
The "prev" field points to the previous node in the list, or NULL if
no such node exists.
With this representation, an empty list is unchnaged
This is the end of the preview.
Sign up
to
access the rest of the document.
 Winter '08
 Phillips

Click to edit the document details