读书人

小弟我的代码错哪了为什么新的链表的

发布时间: 2012-03-29 12:53:12 作者: rapoo

我的代码哪里错了,为什么新的链表的结点就9个
#include<iostream>
#include <ctime>
#include<cstdlib>
using namespace std;
class slist
{
public:
int data;
slist* next;
};
slist* first;

slist* create()
{
slist* newnode=NULL;
slist* back;
first=NULL;
cout<<"the old items of list:";
for(int i=0;i<10;i++)
{
back=newnode;//back指向newnode
newnode=new slist;//建立新的节点
newnode->data=rand()%100;
cout<<newnode->data<<" ";
newnode->next=NULL;
if(first==NULL)
first=newnode;//first指向newnode
else
{
back->next=newnode;
}
}
back->next=NULL;
// delete newnode;
cout<<endl;
return first;
}
slist* reverse(slist* first)
{
if(first!=NULL&&first->next!=NULL)
{
slist* p=first;
slist* q=first->next;
p->next=NULL;
while(q->next!=NULL)
{
first=q->next;
q->next=p;
p=q;
q=first;
}
first->next=p;
}
return first;
}


void showlist(slist* first)
{
cout<<"the new items of list:";
for(int i=0;i<=9;i++)
{
cout<<first->data<<" ";
first=first->next;
}
cout<<endl;
}
void main()
{
slist * sfirst = create();
sfirst = reverse(sfirst);
showlist(sfirst);
}





[解决办法]
back->next=NULL;
把倒数第二个的next改为NULL了。
建议把back=newnode;//back指向newnode
挪到循环的最后一句吧
for(int i=0;i<10;i++)
{

newnode=new slist;//建立新的节点
newnode->data=rand()%100;
cout<<newnode->data<<" ";
newnode->next=NULL;
if(first==NULL)
first=newnode;//first指向newnode
else
{
back->next=newnode;
}
back=newnode;//back指向newnode
}

读书人网 >C++

热点推荐