【发布时间】:2021-05-15 13:51:32
【问题描述】:
我在 C++ 中为链表中的 Insert At Tail 函数编写了这段代码,但是当列表为空时,它不会插入数据。
这是它的图片:- https://i.stack.imgur.com/wKkXk.png
不知道为什么第 35 到 39 行没有执行。
这是我的代码:-
#include <iostream>
using namespace std;
class node
{
public:
int data;
node *next;
// Constructor
node(int d)
{
data = d;
next = NULL;
}
};
void display(node *head)
{
if (head == NULL)
{
cout << "The list is empty !!" << endl;
}
while (head != NULL)
{
cout << head->data << "->";
head = head->next;
}
cout << endl;
}
void Insert_At_Tail(node *head, int data)
{
if (head == NULL)
{
head = new node(data);
return;
}
node *tail = head;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = new node(data);
return;
}
int main()
{
node *head = NULL;
int data;
cout << "Enter the data: ";
cin >> data;
Insert_At_Tail(head, data);
display(head);
return 0;
}
这是我输出的快照:https://i.stack.imgur.com/FFGj6.png
【问题讨论】:
标签: c++ data-structures linked-list