Computer Science 112a
C and Data Structures
Fall 1995
Final examination
Name:
112a-ax account:
The exam is open book: you may consult your notes, books, even computer programs that you
have written before. All the work should be yours.
Show all your work: you may get partial credit. Add extra sheets if necessary.
1. (10 points) Given the following code:
struct node{
int data;
struct node *next;
};
void zaptest()
{
struct node *head, a1, a2, a3, a4;
head = &a1;
a1.data=1; a1.next = &a2;
a2.data = 2; a2.next = &a3;
a3.data = 3; a3.next = &a4;
a4.data = 4; a4.next = NULL;
zap(&head, head); /* value of zap not used here */
}
Determine the result (contents of the given variables head, a1, a2, a3 and a4)
after the function call:
zap(&head, head)
where the function zap is defined as follows:
struct node *zap(struct node **head, struct node *ptr)
{
struct node *temp;
if (ptr -> next == NULL)
*head = ptr;
else {
tmp = zap(head, ptr -> next);
tmp -> next = ptr;
ptr -> next = NULL;
}
return(ptr);
}
2. (30 points) Given the following structure definition:
struct b{
int x;
struct b *y;
struct b z;
};
and the following definitions of variables:
struct b v1, *v2, v3[20], *v4[20], **v5;
Which of the following is a valid C expression? (2 points each)
a. v1 -> x
b. v1.x
c. v2 -> y
d. v2 -> y
e. b.x
f. b -> x
g. v3[2].z
h. v3[2] -> z
i. v3[2].z -> x
j. v3[2].y -> x
k. v4[2] -> y
l. v4[2] -> y.x
m. v4[2] -> y -> x
n. *v5 -> x
o. v5 -> x
3. (10 points) Write a short recursive C function to compute the depth of a
binary tree. The depth is the length of the longest path from the root to a leaf.
The program should use the representation of a tree as a pointer to a tree
node, where a tree node is a C structure defined as:
struct tree_node{
int data;
struct tree_node *left;
struct tree_node *right;
}
Name your function depth. It should take as argument a tree. It should check
to see whether the tree is empty (i.e. if it is the NULL pointer). If not, it should
look at the right and left subtrees, compute their depths, then select the largest
one and add one more unit to it. Using this outline, write the C code for the
function depth.
4. (10 points) You are given the following array and the for loop:
int table[100];
int i;
for (i = 0; i