CSC 161 Grinnell College Fall, 2011
Imperative Problem Solving and Data Structures

Laboratory Exercise on Scheme-like Lists in C


This lab applies ideas of box-and-pointer representations and provides practice implementing lists in C.

Background: Lists in Scheme

The reading for this lab describes box-and-pointer diagrams as a graphical model for lists.

  1. Draw box-and-pointer diagrams for each of the following lists:

    ((x) y z)
    (x (y z))
    ((a) b (c ()))

Implementing Scheme List Operations

The reading also describes the implementation of lists in C and presents program scheme-lists.c that presents relevant C functions and several test cases.

Copy program scheme-lists.c to your account, compile it, and run it. This program will serve as the basis for the remaining steps of this lab. Be sure to ask about any sections you do not understand.

  1. Add a function second to this program that returns the second element in a list (if present) or an empty string if the list is null or has only one element. (In this exercise and the subsequent ones, you will want to add lines to main to test your methods.)

  2. Add a function count which counts how many times a specified item appears on a list. count should have two parameters: the list (of type listType) and the desired item (of type char *) for the search. In writing this code, you should use an iterative approach.

  3. Add a function last which returns the last item on the list.

  4. Add a function get-index that finds the first index of the string str in a list. As parameters, it should take a pointer to the list and a string to look for. It should produce i, an integer.

  5. The program scheme-lists.c deallocates all nodes for d's list and also sets d to NULL. However, listDelete would not affect variables a, b, c, or e. For these variables, the nodes have been deallocated, but the variables still refer to the old memory locations. (Thus, the program sets each of these variables to NULL explicitly.)

    1. What happens if try to print list c or d immediately after the statement listDelete (&d); (before the NULL assignments)?

    2. Why do you think you get this result?

Reminder: Complete Evaluation Form

When you have finished this lab, be sure to fill out its evaluation form in the "Lab Evaluation" section for CSC 161 on Pioneer Web.