/* by Jesse H-K
* on Wed June 21, 2006
*/
#include <stdio.h>
#include <stdlib.h>
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 <= 10; x++)
appendNode(&ll, x);
displayLinkedList(&ll);
deleteLinkedList(&ll);
return 0;
}
struct Node *newNode(int data) {
struct Node *node = malloc(sizeof(struct Node));
node->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 */
}
|