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:
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:
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.