【问题标题】:Problem with inserting into a doubly linked list in ascending order按升序插入双向链表的问题
【发布时间】: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;
}

【问题讨论】:

  • 你能补充一下nodedList是如何定义的吗?它不加起来。看起来node 有一个coords pt,而不是你告诉我们的dList
  • 这是标记为 C++,您没有说明任何限制或原因。所以使用std::list 并忘记所有自定义列表hackery。
  • 另外,你要问的这个确切的功能是什么,应该做什么?将coords 元素插入现有列表?
  • 您的插入有问题。对于第一个节点,您设置L.head=temp;L.tail=temp;(这很好,列表只是自引用,或者在那时循环)。当您插入第二个节点时,问题就来了。你没有处理L.head == L.tail的情况,知道是否设置L.head-&gt;next = L.tail = temp。而对于第二个节点,您只需比较 headtailpoint,它们当时是同一个节点。

标签: c++ sorting doubly-linked-list


【解决方案1】:

要插入的节点在中间的情况就是问题所在。您应该向前查看一个节点,而不是查看当前节点。试着把它写在纸上,你会发现这有什么不同:

  node * cur;
  // also start at head here
  cur=L.head;
  while(cur->next->pt.x<temp->pt.x)
    cur=cur->next;
  temp->next=cur->next;
  temp->prev=cur;
  cur->next->prev=temp;
  cur->next=temp;

您还应该考虑将 dList L 作为指向函数的指针传递,并将其作为指针返回:

// this way you won't be making a copy of it, you may run into trouble if you don't have your copy constructor implemented
dList* insert(dList* L,coords point)

希望对你有所帮助。

【讨论】:

  • 没问题。我很高兴能提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-04
  • 1970-01-01
  • 2021-01-20
  • 1970-01-01
  • 2012-02-18
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多