2015-05-17 89 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,然後你傳遞返回值 –

相關問題