读书人

新学的c++链表不知道为何运行就是失

发布时间: 2013-10-17 17:26:17 作者: rapoo

新学的c++链表,不知道为什么运行就是失败了
因为是刚刚学的 写的就是比较简略的 很多功能都没有实现
这是结点类:
class Node
{
private:
int data;
Node *link;
friend class HeaderList;

};
然后是带表头的链表类(主要是实现插入操作):
class HeaderList
{


public:
int n;
HeaderList();
~HeaderList();
bool Insert(int i,int x);
private:
Node* list;
};
然后是链表的cpp
#include <iostream>
#include "HeaderList.h"
using namespace std;
HeaderList::HeaderList()
{
Node* list=new Node;
list->link=list;
n=0;
}

HeaderList::~HeaderList()
{
Node *p;
while (list) {
p=list->link;
delete list;
list=p;
}
}
bool HeaderList::Insert(int i,int x)
{
if (i<-1||i>n-1) {
cout<<"out of bounds"<<endl;
return false;
}
else {
Node* p=list;
for (int j=0; j<=i; j++) {
p=p->link;
}
Node* q=new Node;
q->data=x;
q->link=p->link; (就是在这一行抛出异常的 一直不明白为什么)
p->link=p;
n++;
return true;}
}

最后是main函数:
#include <iostream>
#include "HeaderList.h"
using namespace std;
int main(int argc, const char * argv[])
{
HeaderList p;
p.Insert(-1, 3);
return 0;
}

表示弄了很长时间,运行时就是报错,求大神指教 链表 c++
[解决办法]
HeaderList::HeaderList()
{
Node* list=new Node;
list->link=list;
n=0;
}
这里出现了错误 list 已经是 HeaderList 的私有变量 Node* list 又重复定义 为局部变量 引起
[解决办法]
Node* q=new Node;
q->data=x;
q->link=p->link; (就是在这一行抛出异常的 一直不明白为什么)
p->link=p;
n++;


Node *q=new Node;
q->data=x;
q->link=p->link;
p-link=q;//错在这里!

读书人网 >C++

热点推荐