高手请进!程序纠错(运行异常)

来源:百度知道 编辑:UC知道 时间:2024/06/11 02:31:49
//本程序实现:
/*将具有头结点的单链表的所有指针全部进行导向。要求使用的额外空间

只能为 O(1),时间代价只能为O(n),其中 n 为结点个数。*/

#include<iostream>
#define null 0
using namespace std;

template<class type> class list;

template<class type>
class node
{
friend class list<type>;
private:
type data;
node<type> *next;
};

template<class type>
class list
{
public:
node<type> *head;
void creatlistr();
void invert(node<type> *&k);
int length();
void display();
};

template<class type>
void list<type>::creatlistr()
{
node<type> *s,*r;
type i;
head=new(node<type> );// 创建头结点
r=head;// r始终指向终端结点
puts("input the elements,end with -1:");
while(cin>>i,i!=-1)
{
s=new(node<type>);
s->data=i;
r->next=s;
r=s;

楼主所述代码包含三个小问题:
1、将语句
node<int> *&L=a.head;
移动到语句
a.creatlistr();
后面,原因是,a.head在创建列表之前的取值为不确定。
2、在template<class type>
void list<type>::invert(node<type> *&k)中的语句
while(q!=null)之前添加一行
p->next = null;
表示列表倒向之后,原先的头指针的后续指针应为空。
3、在template<class type>
void list<type>::display()中的语句
for(i=1;i<=n;i++)
修改为
for(i=1;i<n;i++)