リンク リストを実装する C++ プログラムを作成していました。コンパイル時にエラーは発生しませんが、出力ウィンドウでは空白になり、プログラムは次のように終了します
list1.exe に問題が発生したため、終了する必要があります。
デバッガーの応答: プログラムはシグナル SIGSEGV、セグメンテーション違反を受信しました。
メモリ リークが原因かもしれませんが、正確なバグとその修正方法を特定できません。プログラムの何が問題で、何を修正する必要がありますか?
以下はコードです
//Program to implement linked list
#include <iostream>
#include <cstdlib>
using namespace std;
class Node
{
int data;
Node * next;
public:
Node (){}
int getdata(){return data ;}
void setdata(int a){data=a;}
void setnext(Node* c){next=c;}
Node* getnext(){return next;}
};
class linkedlist
{
Node* head;
public:
linkedlist(){head=NULL;}
void print ();
void push_back(int data);
};
void linkedlist::push_back(int data)
{
Node* newnode= new Node();
if(newnode!=NULL)
{
newnode->setdata(data);
newnode->setnext(NULL);
}
Node* ptr= head;
if(ptr==NULL)
{head=newnode;}
while ((ptr->getnext())!=NULL)
{
ptr=ptr->getnext();
}
ptr->setnext(newnode);
}
void linkedlist::print()
{
Node* ptr=head;
if(ptr==NULL)
{cout<<"null"; return;}
while(ptr!=NULL)
{
cout<<(ptr->getdata())<<" ";
ptr=ptr->getnext();
}
}
int main()
{
linkedlist list;
list.push_back(30);
list.push_back(35);
list.print();
return 0;
}