c - I'm trying to add numbers into a linked list in ascending order. what can I fix so it'll work? Here's my code: -


this code supposed put numbers linked list in ascending order. 1 function of program takes keyboard input(int x) user of program.

node* insert(node *head, int x) {     node *newptr;     node *preptr;     node *currentptr;      newptr = malloc(sizeof(node));      if(newptr != null){             newptr->value = x;             newptr->next = null;              preptr = null;             currentptr = head;              while(currentptr != null && x > currentptr->value){                     preptr = currentptr;                     currentptr = currentptr->next;             }              if(preptr == null){                     newptr->next = head;                     head = newptr;             }             else{                     preptr->next = newptr;                     newptr->next = currentptr;             }     } }     int main(void)//calling input function in main     {         node *head = null;         int x=0;         while(x!=-1){                 printf("?: ");                 scanf("%d", &x);                 head=insert(head,x);                 print(head);                 printf("\n");         }         return 0;     }  //it seems put few numbers in, resets 

the main() function asks numerical input, , sends input insert function supposed put numbers in ascending order. sample output:

$ gcc prelab2.c $ ./a.out ?: 4 4 -> null ?: 3 3 -> 4 -> null ?: 9 3 -> 4 -> 9 -> null ?: 7 3 -> 4 -> 7 -> 9 -> null ?: 2 2 -> 3 -> 4 -> 7 -> 9 -> null ?: -1 

there small mistake. in main() method

head=insert(head,x); 

your insert method return nothing (null). head never changed null;

return head; 

just return head in insert method , work fine.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -