連結リストを勉強しているのですがうまく機能しません。
わかる方がいれば、どこが間違っているか教えてください。
Activity::appendの目的は、headがNULLの場合は連結リストの最初のnodeを作成し、もし先にnodeがあった場合は、その後にnodeを生成するといったものです。
しかし、実行して連結リストを表示したところ、一番最後に入力したnodeの情報しか表示されませんでした。
改善すべき点があれば、お願いします。
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
const int SIZE = 20;
const int SIZE2 = 130;
const int SIZE3 = 100;
struct node
{
char name [SIZE];
char explain [SIZE2];
char reason [SIZE3];
int times;
node *next;
};
class Activity
{
public:
Activity();
~Activity();
void read();
void append(char name[], char explain[], char reason[], int times);
void display();
private:
node *head;
};
Activity::Activity()
{
head = NULL;
}
Activity::~Activity()
{
while(head != NULL)
{
node *temp;
temp = head -> next;
delete head;
head = temp;
}
delete head;
}
void Activity::append(char name[], char explain[], char reason[], int times)
{
if(NULL == head)
{
cout << endl;
head = new node;
strcpy(head->name,name);
strcpy(head->explain,explain);
strcpy(head->reason, reason);
head->times = times;
head->next = NULL;
}
else
{
node *current = head;
while(current->next!= NULL)
{
current = current ->next;
}
current->next = new node;
current = current->next;
strcpy(head->name,name);
strcpy(head->explain,explain);
strcpy(head->reason, reason);
head->times = times;
head->next = NULL;
current->next = NULL;
}
}
void Activity::display()
{
if(head == NULL)
return;
node *current = head;
while(current != NULL)
{
cout <<current->name <<endl;
cout <<current->explain << endl;
cout <<current->reason << endl;
cout <<current->times << endl;
cout << endl;
current = current->next;
}
}
int main()
{
Activity my_activity;
char response ='y';
do
{
char name [SIZE];
char explain [SIZE2];
char reason [SIZE3];
int times;
cout <<"Please enter name of activity" << endl;
cin.get(name, SIZE, '\n'); cin.ignore(100, '\n');
cout <<"Please explain detail of it" << endl;
cin.get(explain, SIZE2, '\n'); cin.ignore(100, '\n');
cout <<"please explain why do you want to do" << endl;
cin.get(reason, SIZE3, '\n'); cin.ignore(100, '\n');
cout <<"How many times does it take?" << endl;
cin >> times; cin.ignore(100, '\n');
my_activity.append(name, explain, reason, times);
cout <<"Do you want to continue to append?" << endl;
cin >> response; cin.ignore(100,'\n');
}while(response=='y');
my_activity.display();
}