问题描述
我用 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
解决方法
问题在于您没有在调用方处更改 head
。要么参考头部
void insert_at_tail(node*& head,int data)
或者更好,返回新的头部:
void insert_at_tail(node *head,int data) {
if (!head) return new node(data);
node *tail = head;
while (tail->next != NULL) tail = tail->next;
tail->next = new node(data);
return head;
}
这样称呼:
head = insert_at_tail(head,data);
更好的是将整个内容包装到一个类中,这样您就可以编写 linked_list.insert_at_tail(data)
并且只需要改变其成员。
void Insert_At_Tail(node *head,int data)
在 C++ 中,默认情况下,函数参数通过按值传递。此 head
参数是调用方传入的参数的副本。
head = new node(data);
这会设置新的 head
指针。这很好,但是因为这个 head
是原始参数的副本,所以这对调用者传入的 head
指针绝对没有任何作用。所有这些都是设置函数的 head
参数/变量。这对传递给此函数的 head
没有影响。
您可以执行以下两项操作之一(您的选择):
-
通过引用传递参数
-
return
来自此函数的head
指针的新值(如果head
指针没有更改,则可以与传入的内容保持不变) ,并让调用者保存新的head
指针。