链接列表pop_back()函数问题

时间:2015-10-06 01:33:43

标签: c++ linked-list pop

List.H

void List::pop_back()
{
    if (size == 0)
        cout << "The list is empty and there is no node to pop off the back    of the list" << endl;
    else if (size == 1)
    {
        delete tail;
        head = tail = iterator = NULL;
    }
    else
    {
        NodeRef temp = tail;
        while (iterator->next != NULL)
            iterator = iterator->next;
        tail = iterator;
        delete temp;
        size--;
    }

}
void List::begin() //Set the iterator to the head of the list
{
    iterator = head;
}

void List::push_front(int data)             //Inserting a new node in the front of the list
{
    if (size == 0)                          //If there is no nodes in the list, execute the if statement
    {
        head = new Node(data);              //create a new node, and have head point to it
        tail = head;                        //have tail point to the new node also.

    }
    else                                    //If there are nodes in the list, execute the else statement
    {
        NodeRef newNode = new Node(data);   //create a new node
        newNode->next = head;               //have the next pointer point to the head of the next node.
        head = newNode;                     //have the head pointer point to the new node inserted at the beginning of the list
    }
    size++;                                 //Increment the size counter
}

void List::print()
{
    iterator = head;                        //Have iterator point to the head
    if (size == 0)
        cout << "There is nothing in the list" << endl;
    else
    {
        while (iterator!= NULL)
        {
            cout << iterator->data << endl;         //Display contents in node
            iterator = iterator->next;              //Move to the next node;
        }
    }
}

List.cpp

int main()
{
    List B;

    B.push_front(5);
    B.push_front(4);
    B.push_front(3);
    B.begin();

    B.pop_back();
    B.print();

    return 0;
}

所以我遇到的问题是在调用pop_back()函数后调用print()函数。它弹出最后一个节点,但列表末尾有一个垃圾编号。我相信正在发生的是它正在显示最终节点Next *这是一个地址。我知道它与pop_back()和iterator-&gt;的else部分有关,接下来会导致它指向一个地址。

1 个答案:

答案 0 :(得分:2)

您有两个问题:

  1. else函数的pop_back()条件 - 您遍历列表以结束,并正确释放最后一个节点的内存,但是您没有 new 尾部的next指针指向NULL。新尾部的next指针仍然指向一些随机的未分配内存,实际上是一个错误。
  2. 你实际上并没有移动尾指针。你的内部while()循环只是让迭代器指向与之前相同的尾部。
  3. 尝试将else中的pop_back()语句更改为:

    iterator = head;
    while (iterator->next->next != NULL) {
        iterator = iterator->next;
    }
    tail = iterator;
    delete tail->next;
    tail->next = NULL;
    --size;
    

    此代码假设列表的大小至少为2(上述if语句处理0和1,因此对于此代码示例应该没问题。)