
CSCI-1200 Computer Science II — Spring 2006
Final Exam Practice Problem Solutions
1. Write a function to create a new singly-linked list that is a copy of a sublist of an existing list. The
prototype is:
Node<T>* Sublist(Node<T>* head, int low, int high)
The Node class is:
template <class T>
class Node {
public:
T value;
Node* next;
};
The new list will contain high-low+1 nodes, which are copies of the values in the nodes occupying
positions low up through and including high of the list pointed to by head. The function should
return the pointer to the first node in the new list. For example, in the following drawing the original
list is shown on top and the new list created by the function when low==2 and high==4 is shown
below.
New list
3.1 2.4 8.7 9.4head
2.4 8.7 9.4
nhead
14.2 0.9
Original list
A pointer to the first node of this new list should be returned. (In the drawing this would be the
value of nhead.) You may assume the original list contains at least low nodes. If it contains fewer
than high nodes, then stop copying at the end of the original list.
Solution:
Node<T>* Sublist(Node<T>* head, int low, int high) {
// Skip over the first low-1 nodes in the existing list
Node<T>*p = head;
int i;
for (i=1; i<low; ++i) p = p-> next;
// Make the new head node and make a pointer to the last node in list
Node<T>* new_head = new Node<T>;
new_head->value = p->value;
Node<T> * last = new_head;
// Copy the remaining nodes, one at a time
for (++i, p = p->next; i<=high && p; ++i, p = p->next) {
last->next = new Node<T>;
last->next->value = p->value;
last = last->next;
}
last->next = 0;
}
1