【问题标题】:Trouble adding to back of doubly linked list无法添加到双向链表的后面
【发布时间】:2016-02-23 01:33:11
【问题描述】:
void DoublyLinkedList::addFront(const Bike& e) 
{   

Node* temp = new Node;                      // Create new node.
temp->bike = e;                             // Store data.
temp->next = head;
temp->prev = NULL;                          // Current head is now next of our new node.
head->prev = temp;
head = temp;                                // Our new node is now the new head.
}

void DoublyLinkedList::addBack(const Bike& e) 
{   

Node* temp = new Node;          // Create new node
temp -> bike = e;
temp -> next = NULL;
temp -> prev = tail;            // our new nodes prev is now the tail
tail -> next = temp;
tail = temp;                    // the tail equals the new node                                 
}

我的 add front 方法工作得很好,但是 addBack 方法没有失败,但是当我显示列表时,没有像 add front 那样显示新节点。

知道是什么原因造成的吗?我迷路了

编辑:更新代码以包含建议

【问题讨论】:

  • 它必须以某种方式。我在这个列表的尾部/上一个方面遇到了问题
  • addFront not 工作得很好。如果您向后浏览列表,您将找不到addFront 添加的节点。
  • 谢谢!我现在看到了错误。
  • 没有足够的代码来真正回答这个问题。我对您的方法被称为 SinglyLinkedList 并且显然是双重的事实感到困惑。代码看起来很简单,但我需要看看头和尾是什么。

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


【解决方案1】:

您正确地初始化了新节点的nextprev 指针(在适当的情况下)。

但是,当添加到非空列表的头部时,您忘记将以前的头部节点的prev 指针设置为列表头部的新节点;并且在添加到非空列表的尾部时,您忘记将前尾部节点的next 指针设置为列表尾部的新节点。

【讨论】:

    【解决方案2】:

    最终为我工作的代码是

      void DoublyLinkedList::addFront(const Bike& e) 
     {  
     if(empty()){
        Node* temp = new Node;                      // Create new node.
        temp->bike = e;                             // Store data.
        temp->next = head;                          // Current head is now next of our new node.
        temp->prev = head;
        head = temp; 
        tail = temp;
        quantity++;
    }
    else{
        Node* temp = new Node;
        temp -> bike = e;
        temp -> next = head;
        temp -> next -> prev = temp;
        temp -> prev = NULL;
        head = temp;
        quantity++;
    }
    }
    
    
    void DoublyLinkedList::addBack(const Bike& e) 
    {   
    Node* temp = new Node;          // Create new node
    temp -> bike = e;
    temp -> prev = tail;            // our new nodes prev is now the tail
    temp -> prev -> next = temp;
    temp -> next = NULL;
    tail = temp;                    // the tail equals the new node 
    quantity++;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多