[英]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.