所以我试图在c ++中改进这段代码。这样做会创建两个类:Student
和Studentlist
。关于改进链表数据结构的任何建议都将不胜感激。
#include <iostream>
using namespace std;
//declaring a class student
class Student
{
public:
char *RollNo;
Student *next;
//function student that includes arguments roll number and a pointer poniting to next node student
Student(char *rollNo, Student *Next)
{
this->RollNo = rollNo;
this->next = Next;
}
//fucntion to get roll number
char* getRollNo()
{
return RollNo;
}
//function to get the pointer to next node named student
Student *getNext()
{
return next;
}
void setNext(Student *aNode)
{
this->next = aNode;
}
};
//declareing a class StudentList
class StudentList
{
public:
Student *head;
// default constructor
StudentList()
{
head = NULL;
}
void Add(char *aRollNo)
{
Student *newStudent = new Student(aRollNo, NULL);
Student *temp = head;
if (temp != NULL)
{
while (temp->getNext() != NULL)
{
temp = temp->getNext();
}
temp->setNext(newStudent);
}
else
{
head = newStudent;
}
}
void display()
{
Student *temp = head;
if (temp == NULL)
{
cout << "no student data in the Student List" << endl;
return;
}
if (temp->getNext() == NULL)
{
cout << temp->getRollNo();
}
else
{
do
{
cout << temp->getRollNo() << " --next--> ";
temp = temp->getNext();
} while (temp != NULL);
cout << " end --> null" << endl;
}
}
};
main()
{
StudentList list;
list.Add("My Roll Number is 411\n");
list.display();
cout << "--------------------------------\n";
system("pause");
return 0;
}
答案 0 :(得分:0)
main()
的声明尚未完成。
main()
请参阅What is the proper declaration of main?
字面值字符串的类型也为char const*
。因此,您的方法调用Add(&#34; XXX&#34;)在类中没有匹配点。你最接近的是Add(char*)
,它与const部分不匹配。
我个人会避免在C ++中使用C-Strings。你应该看看使用std::string
来处理字符串,它可以避免很多问题。
答案 1 :(得分:0)
虽然您总是在最后添加,但我建议您将添加算法代码替换为此
Student* Add(char *aRollNo,Student* last)
{
Student *newStudent = new Student(aRollNo, NULL);
Student *temp = last;
if (head == NULL){
head=newStudent;
temp=head;}
else
temp=temp->setNext(newStudent);
return temp;
}