繁体   English   中英

按升序插入双向链表的问题

[英]Problem with inserting into a doubly linked list in ascending order

我需要创建一个函数来对 2 个分段线性函数(递减或递增)求和,并根据每个点的 x 轴坐标按升序将它们插入到第三个列表中。 所以我创建了多个功能,除了这个功能之外,所有功能似乎都检查出来了,但我不知道有什么问题。 它根本没有输入任何东西。

struct coords有双 x,y;
dList有:坐标点;
节点有:节点*头,*尾;
节点*上一个,*下一个;

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 * 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)

我希望这对你有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM