2015-05-17 54 views
0

所以我想改善这个代码在c + +。这是什么创建了两个类:StudentStudentlist。任何有关改善链表数据结构的建议都将不胜感激。我还能做些什么来改善这个C++代码

#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; 
} 
+7

我认为你正在寻找[代码审查(HTTP更换您添加算法代码://codereview.stackexchange。 com /) – Barry

+2

此代码属于代码审查,不是SO。 – duffymo

+1

只要代码正在工作,那么它[CodeReview](http://codereview.stackexchange.com/)就是如何改进代码的好地方。但目前代码不能编译。首先得到固定的,否则它将被关闭作为脱离主题。 –

回答

0

main()的声明未完成。

main() 

What is the proper declaration of main?

而且文字字符串的类型为char const*。所以你的方法调用Add(“XXX”)在类中没有匹配点。最近的是Add(char*),它与常量部分不匹配。

我个人会避免在C++中使用C-Strings。你应该看看使用std::string来处理字符串,这将避免许多问题。

0

,而你总是在最后加我recomended你这个

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;  
} 
+0

如果你正在寻找速度,这将是一个很好的算法添加 ,特别是如果你有一长串学生,那么while循环将花费相当长的处理器时间,首先你传递NULL,然后你传递返回值 –

相关问题