Programming Fundamentals

Download list_length.c here

Or, copy these file(s) to your CSE account using the following command:

1511 fetch-activity list_length

Your task is to add code to this function in list_length.c:

// Return the length of the linked list pointed by head
int length(struct node *head) {

    // PUT YOUR CODE HERE (change the next line!)
    return 42;

}

For this exercise, you will be given a linked list nodes containing integers, shown below.

struct node {
    struct node *next;
    int          data;
};

Your job is to complete the length function.

length is given one argument, head, which is the pointer to the first node in a linked list.

Add code to length so that its returns the length of the list.

For example if the linked list contains these 8 elements:

1, 7, 8, 9, 13, 19, 21, 42

length should return 8.

Testing

list_length.c also contains a main function which allows you to test your length function.

This main function:

  1. scans in number of items in the list, and its values; to create a linked list,
  2. assigns a pointer to the first node in the linked list to head,
  3. calls list_length(head), then
  4. prints the result.

Do not change this function. If you want to change it, you have misread the question.

Your list_length function will be called directly in marking. The main function is only to let you test your list_length function

Examples

dcc list_length.c -o list_length
./list_length 
How many numbers in initial list?: 9
1 2 3 6 5 4 9 9 0
Counted 9 elements in linked list.
./list_length
How many numbers in initial list?: 6
1 2 3 6 5 4
Counted 6 elements in linked list.
./list_length
How many numbers in initial list?: 5
1 2 3 4 5
Counted 5 elements in linked list.
./list_length 
How many numbers in initial list?: 2
42 4
Counted 2 elements in linked list.
./list_length
How many numbers in initial list?: 0
Counted 0 elements in linked list.

Assumptions/Restrictions/Clarifications