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:
next
", and there is
"x->next
" which is member data of an element. They are related,
but are not the same thing. "next
" holds "x->next
"
after x has been deleted. (Remember, once we delete something, we aren't
allowed to look at it anymore.)
for (x = head; x != NULL; x = x->next) process *x;
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.
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
.