簡體   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