After almost 3 years, I've started relearning C
.
I've created a Linked list
, and would like to extend this to creating a sorted linked list. Here is my code:
typedef struct node{
int data;
struct node *ptr;
}node;
node* insert(node* head, int num){
node *temp,*prev,*next;
temp = (node*)malloc(sizeof(node));
temp->data = num;
temp->ptr = '\0';
if(head=='\0'){
head=temp;
}else{
next = head;
prev = next;
while(next->data<=num){
prev = next;
next = next->ptr;
}
if(next==NULL){
prev->ptr = temp;
}else{
temp->ptr = prev->ptr;
prev-> ptr = temp;
}
}
return head;
}
void main(){
int num;
node *head, *p;
head = '\0';
do{
printf("Enter a number");
scanf("%d",&num);
if(num!=0)
head = insert(head,num);
}while(num!=0);
p = head;
printf("\nThe numbers are:\n");
while(p!='\0'){
printf("%d ",p->data);
p = p->ptr;
}
}
This is my idea. I traverse the list till I find a number >=
the input. I store the previous node in prev
and next
node contains the current value. If next is null
, then the list is ended and the number is the highest among the list so it is to be inserted in the last place, if the number is some where in the middle then, prev node's address part is stored in temp nodes address part now temp node pointer holds address of next node.
Edit: Problem with my code is if I enter 1,2 I get error message as a.exe has stopped working
. I am using MinGW for compiling. I am breaking the loop when user inputs 0.