1. Lab 08 part 3 intro
2. Traversing
3. Searching
4. Inserting
5. Better insert
6. Deleting
Grading

[All of lab 08]
[All labs]
[Course home page]

Traversing a linked list in C

Here is my declaration of a struct suitable for constituting the items of our linked list for this lab:

	struct item {
	    int key;
	    int data;
	    struct item *next;
	};

There will be a global variable named "head" containing a pointer to the first item of the list, or NULL if the list is empty. Write a suitable declaration for this variable.

[formulate your declaration, then click here to reveal my solution]

Now please examine the file /u/csc209h/summer/pub/lab/08/2.c . The "filllist()" function fills up a linked list in a rather silly and awkward way, but it will suffice for this earlier part of the lab. Your task is to write the "printall()" function, whose output will look like this, traversing the linked list:

	5: 0
	20: 2
	22: 6
	38: 3
	[end]
This output means that key 5 has data 0, key 20 has data 2, and so on. After outputting all of the nodes of the list, output "[end]" as shown above.

To traverse the list, you will need a pointer variable of type pointer-to-struct-item. If a pointer variable 'p' is not null, you can advance to the next item with "p = p−>next". (However if p is null (or uninitialized), "p−>next" is an error, of course.)

Please work on this in a file named "2.c" (starting with my 2.c), and submit this file in the usual way, specifically

	submit -c csc209h -a lab08 2.c

Please work on it yourself before looking at my solution in /u/csc209h/summer/pub/lab/08/2s.c ('s' for "solution"). Remember always to compile with "gcc −Wall" and to pay attention to and fix any error messages, even if they are classified as merely "warnings". Your TA can help you with error messages, but please don't ask why your program is not functioning if "gcc −Wall" is giving error messages, because those error messages are probably why! Ask for help with the error messages first. Your submitted version needs to compile with no errors or warnings.

(If you like you can improve your 2.c based on my 2s.c and resubmit, but code copied directly from my 2s.c may not be submitted for credit (and all use of the 'submit' command is for credit).)

Next, we will write code to search the linked list.