C++ 链表打印不工作。。?

C++ 链表打印不工作。。?,c++,C++,第一次建立一个链表,由于某种原因,我没有得到预期的输出。我已经搜索了其他帖子并将其抽出,但仍然没有找到问题。任何见解都值得赞赏。我在头部插入了2个,在尾部插入了7个,当我在main中调用print时,只有2个被打印出来 void List::print() { if (length == 0) cout << "The list is empty!" << endl; else { Nodeptr temp = head; //temporary iterato

第一次建立一个链表,由于某种原因,我没有得到预期的输出。我已经搜索了其他帖子并将其抽出,但仍然没有找到问题。任何见解都值得赞赏。我在头部插入了2个,在尾部插入了7个,当我在main中调用print时,只有2个被打印出来

void List::print()
{
if (length == 0)
    cout << "The list is empty!" << endl;
else
{

Nodeptr temp = head; //temporary iterator

while (temp != NULL)
{
    cout << temp->data << " ";

    temp = temp->nextNode;
}

    cout << endl;
}
}


void List::insert_head(int data)
{
if (length == 0)
{
    head = new Node(data);
    tail = head;
}

else
{
    Nodeptr N = new Node(data); //create node by calling constructor

    N->nextNode = head; // set new nodes next to point to current head
    head = N; //make the head the new node
}

length++;
}

void List::insert_tail(int data)
{
if (length == 0)
{
    head = new Node(data);
    tail = head;
}
else
{
    Nodeptr N = new Node(data);

    N->nextNode = head;
    tail = N;

}

length++; //increase the list length
}
void List::print()
{
如果(长度==0)

cout为什么要在insert_tail()中将新节点指向头部?需要将列表中的最后一个条目链接到新节点

您已经将节点(2)作为头部和尾部显示,只需将节点(7)添加到末端:

Nodeptr N = new Node(data);
tail->nextNode = N;    
tail = N; // now head points to 2, tail points to 7

为什么要在insert_tail()中将新节点指向头部?需要将列表中的最后一个条目链接到新节点

您已经将节点(2)作为头部和尾部显示,只需将节点(7)添加到末端:

Nodeptr N = new Node(data);
tail->nextNode = N;    
tail = N; // now head points to 2, tail points to 7

就我分析您的代码而言,我看到您形成的LL是

尾部-->7-->2->NULL

头在哪里

头->2->空

您需要将insert_tail代码更改为

tail->nextNode=N

尾=N

现在是head->2->7->NULL&tail->7->NULL


希望它能帮助您!

在我分析您的代码时,我发现您形成的结果是

尾部-->7-->2->NULL

头在哪里

头->2->空

您需要将insert_tail代码更改为

tail->nextNode=N

尾=N

现在是head->2->7->NULL&tail->7->NULL


希望它能帮助你!

也许你也应该发布列表和主目录的定义。也许你也应该发布列表和主目录的定义。