I'm having problems displaying the elements in this linked list. Whenever the program runs, it just displays the last element that was entered and not all. The program also stops if I try to delete an element. Please help me, guys. Thank you!
Code:
#include <stdio.h>
#include <stdlib.h>
void display_menu();
int get_choice();
void add_new();
void delete_element();
void display_all();
void insert_beginning();
void insert_middle();
void insert_end();
void delete_beginning();
void delete_middle();
void delete_end();
typedef struct list {
int data;
struct list *next;
} lists;
lists *head, *tail;
main() {
int choice;
do{
display_menu();
choice=get_choice();
switch (choice) {
case 1: add_new(); break;
case 2: delete_element(); break;
case 3: display_all(); break;
case 4: break;
}
} while (choice!=4);
}
void display_menu() {
printf ("MENU\n");
printf ("[1] Add new\n");
printf ("[2] Delete element\n");
printf ("[3] Display all\n");
}
int get_choice() {
int choice;
printf("\nYour choice: ");
scanf ("%d", &choice);
return choice;
}
void add_new() {
int number;
lists *node;
head=NULL;
tail=NULL;
node=(lists *)malloc(sizeof(lists));
printf ("Input an integer: ");
scanf ("%d", &(node->data));
if (head==NULL) {
head=node;
tail=node;
tail->next=NULL;
} else {
if (node->data <= head->data)
insert_beginning();
else
if (node->data >= tail->data)
insert_end();
else
insert_middle();
}
}
void insert_beginning() {
lists *node;
node->next=head;
head=node;
}
void insert_middle() {
lists *temp, *node;
while (temp->next->data <= node->data)
temp=temp->next;
}
void insert_end() {
lists *node;
tail->next=node;
tail=node;
tail->next=NULL;
}
void delete_element() {
int num;
lists *node;
printf ("\nData to be deleted? ");
scanf ("%d", &num);
if (head->data==num)
delete_beginning();
else {
if (tail->data==num)
delete_end();
else
delete_middle();
}
display_menu();
}
void delete_beginning() {
lists *temp;
temp=head;
head=head->next;
free(temp);
display_menu();
}
void delete_middle() {
int num;
lists *temp;
head->next=temp;
while (temp!=NULL){
if (temp->data==num)
free(temp);
}
display_menu();
}
void delete_end() {
lists *temp;
tail=temp;
temp->next=NULL;
tail=temp->next;
free (temp);
display_menu();
}
void display_all() {
lists *temp;
if (head==NULL)
printf ("No elements to print!\n");
else {
temp=head;
do {
printf ("%d\n", temp->data);
temp=temp->next;
} while (temp!=NULL);
}
}