10-linkedlist
10-linkedlist
Linked Lists
15-122: Principles of Imperative Computation (Spring 2017)
Frank Pfenning, Rob Simmons, André Platzer
1 Introduction
In this lecture we discuss the use of linked lists to implement the stack and
queue interfaces that were introduced in the last lecture. The linked list im-
plementation of stacks and queues allows us to handle lists of any length.
This fits as follows with respect to our learning goals:
2 Linked Lists
Linked lists are a common alternative to arrays in the implementation of
data structures. Each item in a linked list contains a data element of some
type and a pointer to the next item in the list. It is easy to insert and delete
elements in a linked list, which are not natural operations on arrays, since
arrays have a fixed size. On the other hand access to an element in the
middle of the list is usually O(n), where n is the length of the list.
3 List segments
A lot of the operations we’ll perform in the next few lectures are on segments
of lists: a series of nodes starting at start and ending at end.
start end
sequence 7, and the data in the segment from a1 to a1 is the empty sequence.
Note that, if we compare the pointers a1 and a3, C0 will tell us they are not
equal — even though they contain the same data they are different locations
in memory.
Given an inclusive beginning point start and an exclusive ending point
end, how can we check whether we have a segment from start to end? The
simple idea is to follow next pointers forward from start until we reach end.
If we reach NULL instead of end then we know that we missed our desired
endpoint, so that we do not have a segment. (We also have to make sure
that we say that we do not have a segment if either start or end is NULL, as
that is not allowed by our definition of segments above.) We can implement
this simple idea in all sorts of ways:
Recursively:
1 bool is_segment(list* start, list* end) {
2 if (start == NULL) return false;
3 if (start == end) return true;
4 return is_segment(start->next, end);
5 }
In code:
1 bool is_acyclic(list* start) {
2 if (start == NULL) return true;
3 list* h = start->next; // hare
4 list* t = start; // tortoise
5 while (h != t) {
6 if (h == NULL || h->next == NULL) return true;
7 h = h->next->next;
8 //@assert t != NULL; // faster hare hits NULL quicker
9 t = t->next;
10 }
11 //@assert h == t;
12 return false;
13 }
A few points about this code: in the condition inside the loop we exploit
the short-circuiting evaluation of the logical or ‘||’ so we only follow the
next pointer for h when we know it is not NULL. Guarding against trying to
dereference a NULL pointer is an extremely important consideration when
writing pointer manipulation code such as this. The access to h->next and
h->next->next is guarded by the NULL checks in the if statement.
This algorithm is a variation of what has been called the tortoise and the
hare and is due to Floyd 1967.
also want both front and back not to be NULL so it conforms to the pic-
ture, with one element already allocated even if the queue is empty; the
is_segment function we already wrote enforces this.
9 bool is_queue(queue* Q) {
10 return Q != NULL
11 && is_acyclic(Q->front)
12 && is_segment(Q->front, Q->back);
13 }
To check if the queue is empty we just compare its front and back. If
they are equal, the queue is empty; otherwise it is not. We require that we
are being passed a valid queue. Generally, when working with a data struc-
ture, we should always require and ensure that its invariants are satisfied
in the pre- and post-conditions of the functions that manipulate it. Inside
the function, we will generally temporarily violate the invariants.
15 bool queue_empty(queue* Q)
16 //@requires is_queue(Q);
17 {
18 return Q->front == Q->back;
19 }
To obtain a new empty queue, we just allocate a list struct and point both
front and back of the new queue to this struct. We do not initialize the list
element because its contents are irrelevant, according to our representation.
Said this, it is good practice to always initialize memory if we care about
its contents, even if it happens to be the same as the default value placed
there.
21 queue* queue_new()
22 //@ensures is_queue(\result);
23 //@ensures queue_empty(\result);
24 {
25 queue* Q = alloc(queue); // Create header
26 list* dummy = alloc(list); // Create dummy node
27 Q->front = dummy; // Point front
28 Q->back = dummy; // and back to dummy node
29 return Q;
30 }
To enqueue something, that is, add a new item to the back of the queue,
we just write the data into the extra element at the back, create a new back
Lecture 10: Linked Lists 10
element, and make sure the pointers are updated correctly. You should
draw yourself a diagram before you write this kind of code. Here is a
before-and-after diagram for inserting 3 into a list. The new or updated
items are dashed in the second diagram.
In code:
32 void enq(queue* Q, elem x
33 //@requires is_queue(Q);
34 //@ensures is_queue(Q);
35 {
36 list* new_dummy = alloc(list); // Create a new dummy node
37 Q->back->data = x; // Store x in old dummy node
38 Q->back->next = new_dummy;
39 Q->back = new_dummy;
40 }
Finally, we have the dequeue operation. For that, we only need to
change the front pointer, but first we have to save the dequeued element
in a temporary variable so we can return it later. In diagrams:
Lecture 10: Linked Lists 11
And in code:
42 elem deq(queue* Q)
43 //@requires is_queue(Q);
44 //@requires !queue_empty(Q);
45 //@ensures is_queue(Q);
46 {
47 elem x = Q->front->data;
48 Q->front = Q->front->next;
49 return x;
50 }
Lecture 10: Linked Lists 12
Let’s verify that our pointer dereferencing operations are safe. We have
Q->front->data
which entails two pointer dereference. We know is_queue(Q) from the
precondition of the function. Recall:
9 bool is_queue(queue Q) {
10 return Q != NULL
11 && is_acyclic(Q->front)
12 && is_segment(Q->front, Q->back);
13 }
We see that Q->front is okay, because by the first test we know that Q != NULL
is the precondition holds. By the second test we see that both Q->front and
Q->back are not null, and we can therefore dereference them.
We also make the assignment Q->front = Q->front->next. Why does
this preserve the invariant? Because we know that the queue is not empty
(second precondition of deq) and therefore Q->front != Q->back. Be-
cause Q->front to Q->back is a valid non-empty segment, Q->front->next
cannot be null.
An interesting point about the dequeue operation is that we do not ex-
plicitly deallocate the first element. If the interface is respected there cannot
be another pointer to the item at the front of the queue, so it becomes un-
reachable: no operation of the remainder of the running programming could
ever refer to it. This means that the garbage collector of the C0 runtime sys-
tem will recycle this list item when it runs short of space.
7 bool is_stack(stack* S) {
8 return S != NULL
9 && is_acyclic(S->top)
10 && is_segment(S->top, S->bottom);
11 }
Popping from a stack requires taking an item from the front of the
linked list, which is much like dequeuing.
30 elem pop(stack* S)
31 //@requires is_stack(S);
32 //@requires !stack_empty(S);
33 //@ensures is_stack(S);
34 {
35 elem x = S->top->data;
36 S->top = S->top->next;
37 return x;
38 }
To push an element onto the stack, we create a new list item, set its data
field and then its next field to the current top of the stack — the opposite
end of the linked list from the queue. Finally, we need to update the top
Lecture 10: Linked Lists 14
field of the stack to point to the new list item. While this is simple, it is still
a good idea to draw a diagram. We go from
to
In code:
40 void push(stack* S, elem x)
41 //@requires is_stack(S);
42 //@ensures is_stack(S);
43 {
44 list* p = alloc(list); // Allocate a new top node
45 p->data = x;
46 p->next = S->top;
47 S->top = p;
48 }
The client-side type stack_t is defined as a pointer to a stack_header:
50 typedef stack* stack_t;
This completes the implementation of stacks.
Lecture 10: Linked Lists 15
7 Sharing
We observed in the last section that the bottom pointer of a stack_header
structure is unused other than for checking that a stack is empty. This sug-
gests a simpler representation, where we take the empty stack to be NULL
and do without the bottom pointer. This yields the following declarations
typedef struct stack_header stack;
struct stack_header {
list* top;
};
bool is_stack(stack* S) {
return S != NULL && is_acyclic(S->top);
}
and pictorial representation of a stack:
But, then, why have a header at all? Can’t we define the stack simply to be
the linked list pointed by top instead?
Eliminating the header would lead to a redesign of the interface and
therefore to changes in the code that the client writes. Specifically,
2. More dramatically, we need to change the type of push and pop. Con-
sider performing the operation push(S, 4) where S contains the ad-
dress of the stack from the caller’s perspective:
Lecture 10: Linked Lists 16
where p is a pointer to the newly allocated list node. Note that the
stack has not changed from the point of view of the caller! In fact,
from the caller’s standpoint, S still points to the node containing 3.
The only way for the caller to access the updated stack is that the
pointer p be given back to it. Thus, push must now return the updated
stack. Therefore, we need to change its prototype to
stack_t push(stack_t S, elem x);
The same holds for pop, with a twist: pop already returns the value
at the top of the stack. It now needs to return both this value and the
updated stack.
With such header-less stacks, the client has the illusion that push and pop
produces a new stack each time they are invoked. However, the underlying
linked lists share many of the same elements. Consider performing the
following operations on the stack S above:
stack_t S1 = push(S, 4);
stack_t S2 = push(S, 5);
This yields the following memory layout:
Lecture 10: Linked Lists 17
All three stacks share nodes 3, 2 and 1. Observe furthermore that the second
call to push operated on S, which remained unchanged after the first call.
At this point, a pop on S would result in a fourth stack, say S3, which points
to node 2.
Sharing is an efficient approach to maintaining multiple versions of a
data structure as a sequence of operations is performed on them. Sharing is
not without its perils, however. As an exercise, consider an implementation
of queues such that enq and deq return to their caller a pair of pointers
to the front and back of the underlying linked list (maybe packaged in a
struct). A carefully chosen series of enq and deq operations will break the
queue (or more precisely its representation invariant).
Exercises
Exercise 1. The tortoise-and-hare implementation of circularity checking we gave
has an assertion, t != NULL, which we can’t prove with the given loop invariants.
What loop invariants would allow us to prove that assertion correct? Can we write
loop invariants that allow us to prove, when the loop exits, that we have found a
cycle?
Exercise 2. Consider what would happen if we pop an element from the empty
stack when contracts are not checked in the linked list implementation? When
does an error arise?
Exercise 5. Here’s a simple idea to check that a linked list is acyclic: first, we keep
a copy of the start pointer. Then when we advance p we run through an auxiliary
loop to check if the next element is already in the list. The code would be something
like this:
bool is_acyclic(list* start) {
for (list* p = start; p != NULL; p = p->next)
Lecture 10: Linked Lists 18