我还能做些什么来改善此C 代码



,所以我试图在C 中改进此代码。这会创建两个类:StudentStudentlist。有关改进链接列表数据结构的任何建议,都将不胜感激。

#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 411n");
    list.display();
    cout << "--------------------------------n";
    system("pause");
    return 0;
}

main()的声明未完成。

 main()

查看主声明是什么?

字面字符串也具有char const*的类型。因此,您的方法调用添加(" xxx")在同类中没有匹配点。您拥有的最接近的是Add(char*),它与const部分不匹配。

我个人会避免在C 中使用C弦。您应该考虑使用std::string处理字符字符串,它将避免许多问题。

始终在最后添加时,我建议您用此

替换添加 add 算法代码
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;     
}

相关内容

最新更新