I am new to C, and this is my first attempt at creating a linked list.
If anyone has a minute and could point out any errors or bad practices in this small linked list program, it would be really helpful.
note:
I'm using the get_choice function to run a loop to either delete, insert, locate, print-out links, or exit.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Link_Data {
int value;
struct Link_Data *prev;
struct Link_Data *next;
};
int main(int argc, char *argv[]) {
char declare[] = "Begin...";
printf ("%s\n", declare);
struct Link_Data *head = malloc( sizeof *head );
head->prev = NULL;
head->next = NULL;
head->value = 0;
get_choice(head);
return 0;
}
int get_choice(struct Link_Data *head) {
int choice;
int value;
while ( true ) {
printf ("Enter 1 to delete, 2 to insert, 3 to locate, 4 to print_all, or 0 to quit: ");
scanf ("%d", &choice);
switch (choice) {
case(1):
printf ("Enter value: ");
scanf ("%d", &value);
delete_node(head, value);
break;
case(2):
printf ("Enter value: ");
scanf ("%d", &value);
insert_node(head, value);
break;
case(3):
printf ("Enter value: ");
scanf ("%d", &value);
locate_node(head, value);
break;
case(4):
printf ("Printing list...\n");
print_links(head);
break;
case(0):
return 0;
}
}
}
int delete_node(struct Link_Data *node, int value) {
if (node->next == NULL && node->prev == NULL) {
printf ("List is empty!\n");
return 0;
}
else if (node->next == NULL && node->value != value) {
printf ("Value %d not in list!\n", value);
return 0;
}
else {
if (node->value == value && node->prev != NULL) {
printf ("Deleting %d...\n", value);
struct Link_Data *prev = node->prev;
prev->next = node->next;
free(node);
}
else {
delete_node(node->next, value);
}
}
return 0;
}
int insert_node(struct Link_Data *node, int value) {
if (node->next == NULL) {
printf ("Inserting %d...\n", value);
struct Link_Data *new_link = malloc( sizeof *new_link );
new_link->value = value;
new_link->prev = node;
new_link->next = NULL;
node->next = new_link;
}
else {
insert_node(node->next, value);
}
return 0;
}
int locate_node(struct Link_Data *node, int value) {
if (node->next == NULL && node->value != value) {
printf ("Value %d not in list!\n", value);
}
else {
if (node->value == value) {
printf ("Locating %d...\n", value);
printf ("Value %d in list!\n", value);
}
else {
locate_node(node->next, value);
}
}
return 0;
}
int print_links(struct Link_Data *node) {
if (node->prev == NULL && node->next == NULL) {
printf ("List is empty!\n");
return 0;
}
else {
if (node->prev != NULL) {
printf ("Value: %d\n", node->value);
}
if (node->next == NULL) {
return 0;
}
else {
print_links(node->next);
}
}
return 0;
}