c++实现双向链表,插入函数莫名错误

qq_37466114 2017-09-27 09:25:10
添加和删除都没有问题,但是只要调用插入函数就会出错。

出错代码: StudentList::print() 的 "p = p->next;" 语句。

add()和insert()都重用了addBefore(),但是add()没有问题;remove()和insert()都重用了getNode(),但是remove()没有问题。

如果主函数只调用add(),remove()那么print()没有问题,但是一旦调用insert(),print()便会报错。

经过调试发现,在在insert()返回之后,链表就会被打断。



已经折磨了我好几天,跪求大神解答,无比感激!




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

}
}
...全文
403 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

5,530

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 模式及实现
社区管理员
  • 模式及实现社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧