Hallo everyone , i am supposed to write a program to insert integers into a sorted linked list. and then delete any element the user chooses to. in the code i am unable to insert elements into my linked list. can someone help me?
Thanks in advance
the code is
[C] sorted linked list - Pastebin.com[
^]
What I have tried:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct node {
int key;
struct node *next;
};
struct node* init(){
struct node *head =0;
return head;
}
int isempty(struct node * head){
if(head == NULL)
return 1;
else
return 2;
}
void printList(struct node * head) {
struct node *ptr = head;
printf("\n");
int n;
n=isempty(head);
if(n == 1)
printf("list is empty");
while(ptr != NULL) {
printf("%d ",ptr->key);
ptr = ptr->next;
}
}
void create(struct node * head,int num) {
struct node * tmp = head;
struct node * prev = NULL;
struct node* new = malloc(sizeof(struct node));
new->key = num;
prev = tmp;
int n;
n=isempty(head);
if(n == 1)
head->next = new;
while(tmp != NULL && tmp->key < num){
prev = tmp;
tmp = tmp->next;
}
new->next = tmp;
if(prev !=NULL)
prev->next = new;
}
struct node* delete(struct node * head, int del) {
struct node* current = head;
struct node* previous = NULL;
struct node* temp = NULL;
int n;
n=isempty(head);
if(n == 1) {
printf("list is empty");
return NULL;
}
while(current->key != del) {
if (current == head){
temp = head;
temp = temp->next;
free(head);
head = temp;
}
if(current->next == NULL) {
return NULL;
} else {
previous = current;
current = current->next;
}
}
if(current == head) {
head = head->next;
} else {
previous->next = current->next;
}
return current;
}
int main() {
int op;
int num;
struct node* head;
head=init();
do{
printf("\n Menu \n 1.Insert \n 2.delete element \n 3.display List \n 4. end program ");
printf("n \n \n please enter an option : ");
scanf("%d",&op);
switch (op) {
case 1:
printf("Enter data:");
scanf("%d",&num);
create(head, num);
break;
case 2:
printf("Enter data:");
scanf("%d",&num);
delete(head,num);
break;
case 3:
printList(head);
break;
case 4:
free(head);
exit(0);
default:
printf("\n enter an option : ");
}
}while(1);
}