为什么链表为空时不插入数据

Why linked list is not inserting data when it is empty?

本文关键字:插入 数据 链表 为什么      更新时间:2024-09-21

我用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

void Insert_At_Tail(node *head, int data)

在C++中,默认情况下,函数参数通过值传递。此head参数是调用方传入的参数的副本

head = new node(data);

这将设置新的head指针。这很好,但因为这个head是原始参数的副本,所以它对调用方传入的head指针完全没有任何作用。所有这些操作都是设置函数的head参数/变量。这对传递到此函数的head没有影响。

你可以做两件事中的一件(你的选择(:

  1. 通过参考传递参数

  2. return此函数中head指针的新值(如果head指针没有更改,则可以与传入的值保持不变(,并让调用方保存新的head指针。

问题是您没有在调用者处更改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),并且只需要对其成员进行变异。