Linked Lists

Okay, we started them last time, but didn't get very far. Be forewarned -- the treatment of linked lists in SLL.h and SLL.cpp is different than in your book. Superior, but different. First things first:

The element class

list class

Constructor

Straightforward...just sets head, tail, and current to NULL.

Destructor

    for (x = head; x != NULL; x = x->next)
        process *x;

insert

Here is a series of pictures representing what happens when insert is called in the case in which current points to an element that is neither the head nor the tail. Before anything happens, we have this picture:

The first thing that happens is that a new element is created, called x. x is initialized with the value we intend to insert, the string s. Let's say we want to insert the name "Scott Baker" after "Patrick Roy".

Now that the new element exists, we splice it into the list. First, we adjust the next pointer of x to point to the same thing as current->next.

Now, adjust current's next pointer to point to x, and set current to x.

Et voila! The element is inserted in the list. The process for inserting at the tail is exactly similar, but after the last step, if tail == current, then tail is set to x. The procedure for inserting at the head is a little different. Instead of updating current's next pointer, we update head.

remove

To remove an element from the list:

First thing is to set the pred pointer (a local variable) to the element preceding current. To do this, we must scan through the list. This takes linear time.

Assuming that pred isn't NULL, we set pred->next to current->next.

And finally, we deallocate current and assign current to pred.

If pred is NULL, then we're removing the first element of the list. In this case, we set head to current->next.

To Index Previous Next