Linked List Delete Example (Circular)

#include <stdio.h>
#include <stdlib.h>


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

struct list * createList(int size);
struct list * search(struct list * head, int target);
struct list * deleteItem(struct list *item, 
			 struct list *next );
void printList(struct list *head);

void main() {
	struct list * listHead;
	struct list * item;
	int target = 1;

	listHead = createList(7);
	printList(listHead);

	item = search(listHead, target);

	if (item != NULL) {
		int data;

		if (item->data == target) {
			// item points at node
			data = item->data;
			// use return val THIS IS UGLY
			listHead = deleteItem(item, NULL);
		}
		else {
			// item points at node that points at node
			data = (item->next)->data;
			// don't use return val THIS IS UGLY
			deleteItem(item, item->next);
		}

		printf("found item, value is %d\n", data);
	}
	else
		printf("%s\n", "item not found");

	printList(listHead);
}

struct list * createList(int size) {
	struct list *start = malloc(sizeof(struct list));
	struct list *mover = start;
	int counter;

	start->data = 1;
	start->next = NULL;

	for (counter = 2 ; counter <= size; counter++) {
		mover->next = malloc(sizeof(struct list));
		mover = mover->next;
		mover->data = counter;
	}

	mover->next = start;

	return start;

}


struct list * search(struct list * head, int target) {
	int found = 0;
	struct list *start = head;

	if (head != NULL) {
		found = head->data == target;

		while (!found && head->next != start) {
			found = (head->next)->data == target;
			if (!found) {
				head = head->next;
			}
		}
	}

	if (found)
		return head;
	else
		return NULL;
}

struct list * deleteItem(struct list *item, 
			 struct list *next ) {

	if (next == NULL) { // delete first item
		if (item == item->next) { // first is only item in list
			free(item);
			item = NULL;
		}
		else {
			struct list * temp = item;
			item = item->next;
			while (item->next != temp) { // find last item
				item = item->next;
			}
			item->next = temp->next;  // point last at new first
			item = item->next;		  // put item back to first
			free(temp);
		}
	}
	else { // not first item
		item->next = next->next;
		free(next);
	}

	return item;
}

void printList(struct list *head) {
	struct list *mover = head;
	
	if (head != NULL) {
		printf("%d\n", head->data);
		mover = head->next;
		while (mover != head) {
			printf("%d\n", mover->data);
			mover = mover->next;
		}
	}
	else {
		printf("%s\n", "empty list");
	}

}