Section 27.12 Reverse a Linked List
In this video we’ll continue working on our arbitrarily long integers and examine how to create a backward copy of one such integer.
Note that the typedef
command does not work properly in the environment in which this lecture is recorded, hence its use is avoided for the purpose of the recordings only.
If you cannot see this codecast, please click here.
Check Your Understanding Check Your Understanding
1.
Given the definition of a linked list of digits as in the video, what does the following function do if called with the address of the first digit of a linked list of digits?
void whatAmIDoing(struct digit * start) {
if(start != NULL) {
whatAmIDoing(start->next);
printf("%d", start->num);
}
}
It prints the entire number stored in the linked list in reverse order.
Correct
It prints every other digit of the number stored in the linked list.
Not quite. Try again!
It prints every other digit of the number stored in the linked list, in reverse order.
Not quite. Try again!
It prints the entire number stored in the linked list.
Not quite. Try again!
It produces an endless loop.
Not quite. Try again!
2.
Given again the definition of a linked list of digits as in the video, the following function reverse()
is supposed to reverse a linked list of digits in place, that is, without creating a copy of the list. There is one line missing at the end of the function.
struct digit * reverse(struct digit * start) {
struct digit * prev = NULL;
struct digit * current = start;
struct digit * next;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
/*ADD LINE HERE*/
}
What should be added in place of /*ADD LINE HERE*/
, so that the function correctly reverses the number?
return(prev);
Correct
return(next);
Not quite. Try again!
return(current);
Not quite. Try again!
return(NULL);
Not quite. Try again!