5,530
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
#include "Student.h"
Student::Student() {
this->prior = NULL;
this->next = NULL;
this->name = "";
this->grade = ' ';
this->score = 0;
}
Student::Student(Student& stu) {
this->grade = stu.grade;
this->name = stu.name;
this->score = stu.score;
this->next = stu.next;
this->prior = stu.prior;
}
Student::Student(string name, char grade, int score,Student* p,Student* n){
this->name = name;
this->grade = grade;
this->score = score;
this->prior = p;
this->next = n;
}
Student::~Student(){}
//***************************************************************
//***************************************************************
//***************************************************************
//下面是StudentList类
#include "stdafx.h"
#include "StudentList.h"
//StudentList缺省构造函数初始化时,初始化头结点和尾节点;
//并声明beginMarker和endMarker为静态全局变量;
//再在StudentList中连接头尾节点;
int StudentList::theSize(0);
Student StudentList::beginMarker;
Student StudentList::endMarker("",' ',0,&beginMarker,NULL);
StudentList::StudentList() {
beginMarker.next = &endMarker;
}
StudentList::~StudentList(){
}
//将新建的student添加到s前;
void StudentList::addBefore(Student& s, string name, char grade, int score) {
//student是指向Student对象的指针;
//初始化student时已经让prior和next指向正确位置;
Student *student = new Student(name, grade, score, s.prior, &s);
//将引用s的prior和next指向正确位置
student->prior->next = student;
s.prior = student;
//链表长度改变;
theSize++;
//student对象应该在析构函数释放;
}
bool StudentList::add(string name, char grade, int score)
{ //新建Student对象并添加到尾节点之前;
addBefore(endMarker, name, grade, score);
return true;
}
void StudentList::insert(int index, string name, char grade, int score) {
//用参数新建一个Student对象,插入到index前;
Student& p = this->getNode(index);
addBefore(p, name, grade, score);
//经调试发现,函数返回之后这里的参数name会变为空;
//但是将print()输出从name改为grade也是会出错;
//错误应该是addBefore之后,被传入的那个对象"失效?"了;
return;
}
void StudentList::remove(int index) {
Student* p = &(getNode(index));
p->prior->next = p->next;
p->next->prior = p->prior;
p->prior = NULL;
p->next = NULL;
//链表长度减一;
theSize--;
}
Student StudentList::getNode(int index) {
Student *p = 0;
if (index <= theSize / 2) {
p = &beginMarker;
for (int i = 0; i < index; i++) {
p = p->next;
}
}
if (index > theSize / 2) {
p = &endMarker;
for (int i = theSize + 1; i > index; i--) {
p = p->prior;
}
}
return *p;
}
void StudentList::print() {
Student *p = &beginMarker;
for (int i = 0; i < theSize; i++) {
cout << p->next->grade<< endl;
p = p->next;
}
}