为什么在第一个推压头之后仍然为空
why after the first push head is still null?
我正在尝试创建单链表。在第一次推送之后,head
仍然是空。为什么头在第一次推送后没有更新?
using namespace std;
typedef struct node {
int data; // will store information
node *next; // the reference to the next node
};
void push(node*,int);
void print(node*);
int main()
{
node* head = NULL; //empty linked list
push(head, 2);
if (head == NULL) {
cout << "vrvrvr";
}
push(head, 3);
push(head, 5);
push(head, 2);
//print(head);
getchar();
return 0;
}
void push(node* x, int y){
node *temp = new node();
if (x == NULL) { // check linked list is empty
temp->next = x;
temp->data = y;
x = temp;
}
else {
node *temp1 = new node();
temp1 = x;
while (temp1->next != NULL) { // go to the last node
temp1 = temp1->next;
}
temp1->next = temp;
temp->data = y;
temp->next = NULL;
delete temp1; // 'temp' node will be the last node
}
}
void print(node* x){
node *temp1 = new node();
temp1 = x;
while (temp1->next != NULL) {
cout << temp1->data << endl;
temp1 = temp1->next;
}
}
push
的主要问题是,在函数中对x
所做的更改是函数的本地更改。它不会改变main
中head
的值。
您可以通过将参数类型更改为node*&
来解决此问题。
void push(node*& x, int y) {
...
}
我看到的其他问题都在区块中:
else {
node *temp1 = new node();
temp1 = x;
// Problem 1:
// After this, the memory returned by the previous line is lost.
// It is a memory leak.
while (temp1->next != NULL) { // go to the last node
temp1 = temp1->next;
}
temp1->next = temp;
temp->data = y;
temp->next = NULL;
delete temp1; // 'temp' node will be the last node
// Problem 2:
// You are deleting a node from the linked list.
// The linked list now has a dangling pointer.
}
您可以使用来纠正这些问题
node *temp1 = x;
while (temp1->next != NULL) { // go to the last node
temp1 = temp1->next;
}
temp1->next = temp;
temp->data = y;
temp->next = NULL;
}
建议改进
从
node
的定义中删除typedef
。在您发布的代码中,它是一个悬空的typedef
。此外,您可以在C++中使用不带typedef
的node
。struct node { int data; node *next; };
向
node
添加构造函数。struct node { node(int d) : data(d), next(nullptr) {} int data; node *next; };
这将简化
push
中的代码。void push(node*& x, int y){ node *temp = new node(y); if (x == NULL) { // check linked list is empty x = temp; } else { node *temp1 = x; while (temp1->next != NULL) { // go to the last node temp1 = temp1->next; } temp1->next = temp; } }
相关文章:
- 在类定义之后定义一个私有方法
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 为什么第一个Dynamic_cast没有投射到基类?
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- C++ 为什么程序只读取第一个值
- 在我的第一个C++程序中需要一些帮助(简单)
- 如何在第一个 std::cin 之后阻止终端在 C++ 中关闭
- 当第一个 itr 在最后一个 itr 之后时,std::vector 范围构造函数的官方行为是什么?
- 第一个 rand() 在 srand(time(0) 之后生成相同的值
- 为什么我的第一个 if 语句有效,但我的 else if 语句在它之后不起作用