c - Inserting newNode in ascending order into LinkedList -
i have problem when trying insert newnode linked list in ascending order. here code:
void insertsortedlinkedlist(linkedlist *l, int x) { listnode* newn; listnode *cur, *previous; if (l->head == null) { l->head = malloc(sizeof(listnode)); l->head->item = x; l->head->next = null; } else { newn = malloc(sizeof(listnode)); newn->item = x; cur = l->head->next; previous = l->head; while (cur!= null && cur->item < x) { previous = cur; cur= cur->next; } newn->next = cur; previous->next = newn; } l->size++; }
with these code, entered input 1,3,5,7,9,6
, managed output 1,3,5,6,7,9
in ascending order. however, when tried 3,2,1
, output 3,1,2
. 3 first input not shift.
any idea how fix this?
thanks in advance.
you'e close. problem code can never insert new node head in list has element.
here's 1 idea reorganizing:
void insertsortedlinkedlist(linkedlist *l, int x) { listnode* newn; listnode *cur, *previous; newn = malloc(sizeof(listnode)); newn->item = x; previous = null; cur = l->head; while (cur!= null && cur->item < x) { previous = cur; cur= cur->next; } if (previous == null) l->head = newn; else previous->next = newn; newn->next = cur; l->size++; }
Comments
Post a Comment