
-----------------------------------
Null
Wed Jun 21, 2006 11:32 am

Linked list in C
-----------------------------------
I would appreciate any comments on my own implementation of a linked-list in C.

I'm sure there are quite a few improvements, and it's incomplete. The main goal for me was to write one without any glances at references.



/* by Jesse H-K
 * on Wed June 21, 2006
 */

#include 
#include 

struct Node {
	int data;
	struct Node *next;
};

struct LinkedList {
	struct Node *first;
};

struct Node *newNode(int data);
void newLinkedList(struct LinkedList *list, int data);
void displayLinkedList(const struct LinkedList *list);
void appendNode(struct LinkedList *list, int data);
void deleteLinkedList(struct LinkedList *list);
int findNode(const struct LinkedList *list, int data);
	
int main(void) {
	struct LinkedList ll;
	
	newLinkedList(&ll, 1);

    int x;
	for(x = 2; x data = data;
	node->next = NULL;

	return node;
}

void newLinkedList(struct LinkedList *list, int data) {
	list->first = newNode(data);
}

void displayLinkedList(const struct LinkedList *list) {
	struct Node *current = list->first;

	//traverse the list, printing the data at each Node.
	while(current != NULL) {
		printf("%d\n", current->data);
		current = current->next;
	}
}

void appendNode(struct LinkedList *list, int data) {
	struct Node *current = list->first;
	
	if(list->first->next == NULL) //only one Node
		list->first->next = newNode(data);

	else {
		//go to the last Node in the list
		do {
			current = current->next;
		} while (current->next != NULL);

		//add on a Node that the current Node points to
		current->next = newNode(data);
	}
}

void deleteLinkedList(struct LinkedList *list) {
	struct Node *current;
	struct Node *temp;
	
	if(list->first->next == NULL) //only one Node in the list
		free(list->first);
	else {
		current = list->first;
		
		while(current != NULL) {
			temp = current;
			current = current->next;
			free(temp);
		}
	}
}

int findNode(const struct LinkedList *list, int data) {
	struct Node *current = list->first;

	while(current != NULL) {
		if(current->data == data)
			return 1; /* typecast into true in conditionals */

		current = current->next;
	}
	return 0; /*typecase into false in conditionals */
}


-----------------------------------
wtd
Wed Jun 21, 2006 2:44 pm


-----------------------------------
You may wish to see my C whirlwind tour.  ;)
