[英]Insert an element in the middle of a linked list, in a ordered way?
我得到了我的链表:
typedef struct t_node {
ELEMLIST data;
struct t_node *next;
} NODE;
typedef NODE *LIST;
而且我尝试以有序方式(从较小的数字到较大的数字)插入整数,但似乎有些事情不起作用:
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;
}
当我运行它时,它只是告诉我我的列表为空...
我敢肯定,这只是我错过的一些细节,但是我无法意识到
您的代码错误地完成了几件事:
我完全不知道您的比较功能如何工作。 该代码似乎表明只要列表第一个值“小于”第二个就返回1(这与大多数比较器的工作方式正好相反。大多数这样做:
尽管如此,我还是对您的算法进行了改进。
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;
}
这假设列表为空, *list
将为NULL,并且分配成功。 量身定制,随心所欲。 祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.