为什么链表为空时不插入数据
Why linked list is not inserting data when it is empty?
我用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
没有影响。
你可以做两件事中的一件(你的选择(:
通过参考传递参数
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)
,并且只需要对其成员进行变异。
相关文章:
- 在 QAbstractTableModel 上的 setModel 之后插入数据
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- 增强循环缓冲区push_back在前面插入数据
- 程序 使用链表插入数据时停止工作
- 如何与LIBPQXX API同时插入数据?(PostgreSQL,线程)
- 如何在其中创建2D字符串向量并插入数据
- 二叉搜索树插入数据问题
- 通过指定第 n 个节点位置在单链接列表中插入数据
- 默认情况下构造函数插入数据后,我没有得到任何输出,但我不确定为什么不
- 在std::映射中插入数据
- 插入数据时出现分段错误
- 如何在C++的排序文件中插入数据
- 在二进制树中插入数据时出错
- 在双通道矩阵中插入数据
- 用于插入数据而非搜索的最快数据结构
- 无法在映射的映射的STL映射中插入数据
- 如何插入数据到sqlite使用qt
- 为什么在c++中,在矢量结束后插入数据是错误的
- 在没有c++方法的类中插入数据
- 在矢量中插入数据时多次调用复制构造函数