LIST is a variable of type Node* in our
program, and suppose that it points to the list 87, 42, 53, 4 as illustrated in
the following picture:
ints in a linked list, then print the values stored in a list.
Node* p = LIST;
while(????)
{
cout << p->data << " "; // do whatever you have to do while traversing the list
p = p->next; // move to the next node
}
The last line of the while-loop body,
p = p->next; is what moves us from one node to
the next.
???? with?
p points to the last node (i.e., the node containing 4).
p = p->next is executed, which implies
that the value of p becomes NULL. Recall the
"slash" in the node means that the value of next field is NULL.
(p != NULL) satisfies
our requirements (if you are not convinced, walk the printing code
snippet below using the above linked list example, slowly and node by node,
and convince yourself).
Node* p = LIST;
while( p != NULL )
{
cout << p->data << " ";
p = p->next;
}
LIST is NULL).
for(Node* T = L; T != NULL; T = T->next)
cout << T->data << ' ';
cout << endl;
I really prefer writing it this way, because it makes the
traversal code (the for(Node* T = L; T != NULL; T = T->next))
totally boiler-plate: that stays the same for any kind of list
you ever make, and really no matter what you're doing for the
traversal.
|
|
|
LIST to traverse the list! Create a new pointer.
LIST represents the entire list by pointing to the head of
the list. Unless the list changes, LIST should never be
changed.
A that
represents the array and an index variable i. Think of
p as something similar to A[i].
Again, when scanning, make sure that LIST never changes just as
A never changes.
Node* search(dobule value, Node* L);
Match: The difference of the two numbers is less than 1
Using the function, we can write a program that provides a "search" feature.
|
Sample run
~/$ ./ex 34.2, 54.98, 92.0, 83.9; search 54 Found: 54.98 search 83 Found: 83.9 search 12 Not Found! quit
Question: function definition?Check the solution. |
Node* deletefront(Node* L)
Note that once the front node is deleted, the function should return the
modified list -- now the second node should become the head node.
Node* deletefront(Node* L)
{
if (L == NULL)
return NULL;
Node* second = L->next; // store the 2nd node to return
delete L; // delete the front node
return second;
}
Q: What's wrong with the following simpler (even seemingly more elegant)
function?
|
Answer:
The function goes through the following steps:
step 2
because
Evaluating L->next needs to access the node that L
points to, but that node has already been deleted in step 1
|
void deletelist(Node* L)
{
while (L != NULL)
L = deletefront(L);
}

... 10, 20, 25, 30, 40 ...Give the code performing the task.
Hint:
double's. Check out
my solution. double's. Check out my solution.