简体   繁体   中英

Insert an element in the middle of a linked list, in a ordered way?

I got my linked list:

typedef struct t_node {
    ELEMLIST data;
    struct t_node *next;
} NODE;

typedef NODE *LIST;

And I try to insert the integer in an ordered way (from smaller to bigger numbers), but seems like something's not working:

STATUS insertInOrderList(LIST *list, const ELEMLIST *pElem) {

    NODE *newNode, *nodeIns;

    newNode = getNode();//allocate memory
    nodeIns = getNode();

   //checkout getnode return

    newNode->data = *pElem;

    for (nodeIns = *list; nodeIns != NULL; nodeIns = nodeIns->next) {
        if (cmpEleList(&newNode->data, &nodeIns->data) != 1) { 
             //if arg1 is not > arg2 it breaks the loop
            break;
        }
    }

    newNode->next = nodeIns;
    nodeIns->next = newNode;

    return OK;
}

When I run it it just tell me that my list is empty...

I'm sure it's just some detail I missed, but I just can't realize what

Your code does several things incorrectly:

  • You're allocating two nodes; not one (this isn't Java or C#).
  • You don't account for the possibility that the first node in the list may already be "greater" than the incoming node.
  • You don't wire the new node in correctly.

I have absolutely no idea how your comparison function works. the code seems to indicate it returns 1 so long as the list first value is "less" than the second (which would be exactly the opposite of how most comparators work. most do this:

  • lhs < rhs : return < 0
  • lhs == rhs : return 0
  • lhs > rhs : return > 0

Be that as it may, I retrofitted your algorithm regardless.

STATUS insertInOrderList(LIST *list, const ELEMLIST *pElem) 
{

    NODE *newNode = getNode();
    newNode->data = *pElem;

    while (*list && cmpEleList(&(*list)->data, pElem) != 1)
        list = &(*list)->next;

    newNode->next = *list;
    *list = newNode; 

    return OK;
}

This assumes if the list is empty *list will be NULL, and that the allocation succeeded. Tailor to whatever you wish. Best of luck.

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