【发布时间】:2019-12-30 23:45:57
【问题描述】:
我需要创建一个函数来对 2 个分段线性函数(减少或增加)求和,并根据每个点的 x 轴坐标以升序将它们插入到第三个列表中。所以我创建了多个功能,除了这个之外似乎都检查了,但我不知道是什么问题。它根本没有输入任何东西。
struct coords 有双 x,y;
dList 有 : coords pt;
node 有 : node *head , *尾;
节点 *prev, *next;
dList insert(dList L, coords point) {
node *temp;
temp = new node;
if (temp == NULL) {
cout << "error";
exit(1);
}
temp->next = NULL;
temp->prev = NULL;
temp->pt = point;
if (L.head == NULL || L.tail == NULL) {
L.head = temp;
L.tail = temp;
return L;
}
if (L.head->pt.x > temp->pt.x) {
temp->next = L.head;
L.head->prev = temp;
L.head = temp;
return L;
}
if (L.tail->pt.x < temp->pt.x) {
temp->prev = L.tail;
L.tail->next = temp;
L.tail = temp;
return L;
}
node *cur;
cur = L.head->next;
while (cur->pt.x < temp->pt.x)
cur = cur->next;
temp->next = cur->next;
temp->prev = cur;
cur->next->prev = temp;
cur->next = temp;
return L;
}
【问题讨论】:
-
你能补充一下
node和dList是如何定义的吗?它不加起来。看起来node有一个coords pt,而不是你告诉我们的dList。 -
这是标记为 C++,您没有说明任何限制或原因。所以使用
std::list并忘记所有自定义列表hackery。 -
另外,你要问的这个确切的功能是什么,应该做什么?将
coords元素插入现有列表? -
您的插入有问题。对于第一个节点,您设置
L.head=temp;和L.tail=temp;(这很好,列表只是自引用,或者在那时循环)。当您插入第二个节点时,问题就来了。你没有处理L.head == L.tail的情况,知道是否设置L.head->next = L.tail = temp。而对于第二个节点,您只需比较head和tail的point,它们当时是同一个节点。
标签: c++ sorting doubly-linked-list