Test 1 Addendum, CPS 100, Spring 1997
Problem 1 (6 points)
Write the function MergeList whose header is shown below.
MergeList creates and returns a new sorted list by merging two
sorted lists. In the diagram below, the list returned by a
a call of Merge(first,second) is shown
Node * MergeList(Node * first, Node * second)
// precondition: first and second are sorted, each has a header node
// postcondition: returns pointer to header node of a sorted list
// containing all values in first and second
{
}
Problem 2 (6 points)
Write the function TreeToList that converts a binary search
tree to a sorted linked list. Assume the same declarations
for DNode and TNode as given on the test (reproduced
below). The function TreeToList returns, via reference
parameters, pointers to the first and last nodes of a doubly linked list
with no header node. Hint: you'll need to make two recursive
calls, each recursive call requires passing two DNode *
arguments. This means the easiest thing to do is to declare
four local DNode * variables for passing in the recursive
calls, but you're free to do something else, write auxiliary functions, etc.
// for doubly-linked lists // for binary (search trees)
struct DNode struct TNode
{ {
string info; string info;
DNode * prev; TNode * left;
DNode * next; TNode * right;
DNode(const string & s, TNode(const string & s,
DNode * prior = 0, TNode * lchild = 0,
DNode * after = 0) TNode * rchild = 0)
: info(s), : info(s),
prev(prior), left(lchild),
next(after) right(rchild)
{ } { }
}; };
void TreeToList(TNode * root, DNode * & first, DNode * & last)
// preconditon: root points to root-node of a binary search tree
// postcondition: first points to first node of a sorted linked list
// last points to last node of a sorted linked list
// the linked list contains the values stored in the tree
{
}
Owen L. Astrachan
Last modified: Mon Feb 24 09:37:35 EST