C Programming

Practise Exercise 12: Lists

1. Define a structure called node, which contains an integer element called data, and a pointer to a structure of type node called next_node.


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

2. Declare three structures called node1, node2, node3, of type node.


	struct node node1, node3, node3;

3. Write C statements which will link the three nodes together, with node1 at the head of the list, node2 second, and node3 at the tail of the list. Assign the value NULL to node3.next to signify the end of the list.


	node1.next_node = &node2;
	node2.next_node = &node3;
	node3.next_node = (struct node *) NULL;

4. Using a pointer list, of type node, which has been initialised to the address of node1, write C statements which will cycle through the list and print out the value of each nodes data field.


	while( list != NULL ) {
		printf("%d\n", list->data );
		list = list->next_node;
	}

5. Assuming that pointer list points to node2, what does the following statement do?


	list->next_node = (struct node *) NULL;

	The statement writes a NULL into the next_node pointer, making node2 the end of
	the list, thereby erasing node3 from the list.

6. Assuming the state of the list is that as in 3., write C statements which will insert a new node node1a between node1 and node2, using the pointer list (which is currently pointing to node1). Assume that a pointer new_node points to node node1a.


	new_node.next_node = list.next_node;
	list.next_node = new_node;

7. Write a function called delete_node, which accepts a pointer to a list, and a pointer to the node to be deleted from the list, eg


	void  delete_node(  struct  node  *head,  struct  node  *delnode );


	void  delete_node( struct node *head, struct node *delnode )
	{
		struct node *list;

		list = head;
		while( list->next != delnode ) {
			list = list->next;

		list->next = delnode->next;
	}

8. Write a function called insert_node, which accepts a pointer to a list, a pointer to a new node to be inserted, and a pointer to the node after which the insertion takes place, eg


	void insert_node( struct node *head, struct node *newnode, struct node *prevnode );


	void insert_node( struct node *head, struct node *newnode, struct node *prevnode )
	{
		struct node *list;

		list = head;
		while( list != prevnode )
			list = list->next;

		newnode->next = list->next;
		list->next = newnode;
	}



©Copyright B Brown. 1984-1999. All rights reserved.