[英]I can't figure out why my add method won't work
我可以到达添加节点的位置,但在那之后,程序就会自行切断。
我在 Windows 10 上,使用 VSCode 内部人员。 使用 G++ 作为我的编译器,如果有的话。 我试过只手动设置节点的指针,这是可行的。 我无法弄清楚该方法有什么不同。 这个想法是“tail 是最后一个节点,所以让 tail.next 成为添加的节点并设置 tail 等于新节点。”
#include <iostream>
using namespace std;
struct Node{
int data;
struct Node *next;
};
class List{
private:
struct Node *head;
struct Node *tail;
public:
list(){
head->next=tail;
// I tried initializing tail.next to null but that didn't help
tail->next=NULL;
}
void add(int d){
printf("I'm entering the add\n");
struct Node *n=new Node;
printf("Node created\n");
n->data=d;
printf("Data set %d\n", n->data);
// right here is the issue, it seems
tail->next=n;
printf("Node added\n");
tail=n->next;
}
};
int main(){
List l;
l.add(50);
return 0;
}
我期待它打印 50(我还没有尝试过我的显示方法,因为代码在它到达之前就中断了),但它输出“数据集 50”然后崩溃。 编译正常,没有警告。
主要问题出在您的构造函数中,它的名称应该与 Class 相同(实际上您正在使用 STL 列表)。然后在构造函数中,您应该将头部和尾部都初始化为 NULL。
我已更正的其他小错误,以下是您的代码。
#include <iostream>
using namespace std;
struct Node{
int data;
struct Node *next;
};
class List{
private:
struct Node *head;
struct Node *tail;
public:
List(){
//initialise both head and tail to NULL
tail=NULL;
head=NULL;
}
void add(int d){
printf("I'm entering the add\n");
struct Node *n=new Node;
printf("Node created\n");
n->data=d;
printf("Data set %d\n", n->data);
n->next=NULL;
// I think you missed about the first time when you will add a node
if(head==NULL)//for adding first time , we will have to check as the first will be our last one
{
tail=n;
head=n;
}
else// for second time or more we give new node pointer address to our linked list last node next
{
tail->next=n;
tail=n; // then this n becomes our last node
}
printf("Node added\n");
}
};
int main(){
List l;
l.add(50);
l.add(70);
l.add(90);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.