无法添加到双向链表的后面

时间:2016-02-23 01:33:11

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

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方法没有失败,但是当我显示列表时,没有显示新节点,就像添加前面一样。

任何可能导致这种情况的想法?我失去了

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

2 个答案:

答案 0 :(得分:1)

您已正确初始化新节点的nextprev指针。

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

答案 1 :(得分:0)

最终为我工作的代码是

  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++;
}