调试没错,为什么运行时就有问题啊?到底是哪边有问题呢?
#include <iostream.h>
class ListNode
{
friend class List;
double value;
ListNode * next;
};
class List
{
int nCount;
ListNode * head;
public:
List() //无参构造函数
{nCount=0;
head=NULL;
}
~List() //析构函数
{
ListNode* p = head,*q;
while(p)
{
q = p->next;
delete p;
p = q;
}
}
List & operator = (List & l) //重载等号运算符
{ List l3;
nCount=l.nCount;
ListNode *f,*s;
int i;
s=l3.head;
f=l.head;
for(i=0;i<l.nCount;i++)
{l3.Add(f->value);
f=f->next;
}
head=s;
return l3;
}
void Add(double d) //添加一个元素
{ if (head == NULL)
{
head = new ListNode;
head->value = d;
head->next = NULL;
nCount++;
return;
}
ListNode *p,*q;
p=new ListNode;
p->next=NULL;
q=head;
while(q->next!=NULL)
{q=q->next;
}
q->next=p;
p->value=d;
nCount++;
}
void Remove(double d) //删除一个元素
{ ListNode *p;
if(head->value==d)
{
p = head;
head = head->next;
delete p;
nCount--;
return;
}
p=head->next;
ListNode *s=head;
while(p->value!=d)
{p=p->next;
s=s->next;
}
s->next=p->next;
delete(p);
nCount--;
}
void Print()
{
if( head==NULL) return;
cout << "LIST(" << nCount <<") =" << head->value;
ListNode * p=head->next;
while(p!=NULL)
{
cout << ", "<< p->value;
p=p->next;
}
cout <<endl;
}
};
void main()
{
List list1;
double d;
int n;
cin >>n;
while (n>0)
{
cin >>d;
list1.Add(d);
n--;
}
list1.Print();
List list2;
list2.Add(2.4);
list2.Add(6.1);
list2.Print();
list2=list1;
cin >>d;
list2.Remove(d);
cin >>d;
list2.Remove(d);
list2.Print();
}
[解决办法]
你的代码修改如下:
#include <iostream>using namespace std;class ListNode{ friend class List; double value; ListNode * next;};class List{ int nCount; ListNode * head;public: List() //无参构造函数 {nCount=0; head=NULL; } ~List() //析构函数 { ListNode* p = head,*q; while(p) { q = p->next; delete p; p = q; } } List & operator = (List & l) //重载等号运算符 { if(this->head == l.head) return *this; ListNode *f,*s; s = head; while(head) { s = s->next; delete head; head = s; } nCount = 0;int i;f=l.head;for(i=0;i<l.nCount;i++){Add(f->value);f=f->next;} return *this; } void Add(double d) //添加一个元素 { if (head == NULL) { head = new ListNode; head->value = d; head->next = NULL; ++nCount; return; } ListNode *p,*q; p=new ListNode; p->next=NULL; q=head; while(q->next!=NULL) {q=q->next; } q->next=p; p->value=d; ++nCount; } void Remove(double d) //删除一个元素 { ListNode *p; if(head->value==d) { p = head; head = head->next; delete p;nCount--; return; } p=head->next; ListNode *s=head; while(p &&p->value!=d) {p=p->next; s=s->next; } if(p == NULL) return; s->next=p->next; delete(p); nCount--; } void Print() { if( head==NULL) return; cout << "LIST(" << nCount <<") =" << head->value; ListNode * p=head->next; while(p!=NULL) { cout << ", "<< p->value; p=p->next; } cout <<endl; }};int main(){List list1; double d; int n; cin >>n; while (n>0) { cin >>d; list1.Add(d); n--; } list1.Print(); List list2; list2.Add(2.4); list2.Add(6.1); list2.Print(); list2=list1; cin >>d; list2.Remove(d); cin >>d; list2.Remove(d); list2.Print();return 0;}