简体   繁体   中英

C Linked list inserting element in a sorted way

Hey I need to insert an element into linked list in a sorted way. Each element has isbn which I need the linked list to be sorted with.It kind of works because it inserts the smallest element at the head but that's it the rest seems to be sorted in random way. Here is my code

void insertABook(linkedlist *root, linkedlist *newbook)
{ 
    if ((root==NULL) && (root->ptr==NULL))
    {
        root->ptr=newbook;
    }
    else
    {
        linkedlist *next = root;
        while((next->ptr != NULL) && (next->isbn < newbook->isbn))
        {
            next = next->ptr;
        }
        newbook->ptr=next->ptr;
        next->ptr=newbook;
    }
}

The root parameter is dummy node(NULL) and the newbook parameter is new element to be inserted. I add elements one by one using this method.

The Parameter root is a value that is an address stored in the root.
I guess your code.

    linkedlist *root = NULL, *newbook;
    while (...) {   // or for( , , )
        newbook = malloc(sizeof(linkedlist));
        // edit newbook
        insertABook(root, newbook);
              :
              :

There is at least 3 way.
1. insertABook() return linkedlist* to store the root.

        root = insertABook(root, newbook);

2. change root as linkedlist**. I guess this is the answer what you want.

void insertABook(linkedlist **root, linkedlist *newbook) {
    if (*root==NULL) {
        *root=newbook;
    }
    else {  // insert or append
        linkedlist  *next = *root;
            :
            :

caller

        insertABook(&root, newbook);

&root is an address of root.

  1. root is global within the source file.

     static linkedlist *root = NULL; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM