【发布时间】:2015-10-06 01:33:43
【问题描述】:
列表.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;
}
}
}
列表.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() 的 else 部分和 iterator->next 导致它指向一个地址有关。
【问题讨论】:
-
也许你的问题出在
print函数中——你也能证明一下吗?另外 - 你的弹回依赖于在它之前调用begin的人,这听起来不是一个好主意。 -
为什么你认为最终节点的
next应该指向NULL?我在你的代码中没有看到你让它指向 NULL 的任何地方。 -
@immibis 好问题。我想我的意思是它显示最后一个节点->下一个指向一个空地址,而不是 NULL
-
为什么
iterator是成员变量而不是局部变量? -
@BillLynch 就像我老师让我们写的那样。
标签: c++ linked-list