October 22, 2002
Given a non-circular list with head pointing to its first node, write a piece of code that turns the list into a circular one.
There are various ways of doing this ...
for (tail = head; tail->next != NULL; tail=tail->next); tail->next = head; tail->next->previous = tail;
for (tail = head; tail->next != NULL; tail=tail->next); head->previous = tail; head->previous->next = head;
for (tail = head; tail->next != NULL; tail=tail->next); head->previous = tail; tail->next = head;
tail = head;
do {tail=tail->next} while (tail->next != NULL);
tail->next = head;
tail->next->previous = tail;
A, C, and D definitely don't work. (Note that the loops in C and D stop immediately.) B and E work except on the empty list. Because of that either answer was accepted.
A. length = 0;
- for (current = head;
current->next != head;
current=current->next)
length++;
B. length = 1;
+ for (current = head;
current->next != head;
current=current->next)
length++;
C. length = 0;
- for (current = head;
current != head;
current=current->next)
length++;
D. length = 1;
- for (current = head;
current != head;
current=current->next)
length++;
E. length = 1;
+ for (current = head;
current->previous != head;
current=current->previous)
length++;
void Catalog::deleteSecond ()
{
if (head == NULL)
return;
if (head->next == NULL)
return;
CatalogNode* second = head->next;
head->next = second->next;
if (second->next != NULL)
second->next->previous = head;
delete second;
return;
}