一个链表问题,各位来瞧瞧
- C/C++ code
/*题目: 前N个自然数排成一串: X1,X2,X3.....Xn,先取出x1,将x2,x3移到数串尾,再取出x4,将x5,x6移到数串尾,....... 类推直至取完. 取出的序列恰好是:1,2,3......n.要求输入N,求原来的数串的排列方式. 例如:1,5,3,2,4,经过上述操作后,可得1,2,3,4,5。 */# include<iostream>#include<malloc.h>using namespace std;struct L{ int zhi; struct L *next;};void shuchu(struct L *r) //输出函数{ while(r) { cout<<r->zhi<<" "; r=r->next; }}int main()//主函数{ L *p,*q,*r,*t,*e; int k; cout<<"输入测试数值"<<endl; cin>>k; r=(struct L *)malloc(sizeof(L)); cin>>r->zhi; p=r; int i; i=k-1; while(i>0) { q=(struct L*)malloc(sizeof(L));//当k=3时这里出错 cin>>q->zhi; q=p->next; //当k=4和5时,这里出错 p=q; i--;//当k=2时,这里出错 } p->next=NULL; if(k<=3) { shuchu(r); return 0; } if(k==4) { t=r->next; e=t->next; t->next=p->next; p->next=t; r->next=e; shuchu(r); return 0; } if(k==5) { t=r->next->next; e=t->next; t->next=p->next; p->next=t; r->next->next=e; e=r->next; t->next=e->next; r->next=p; e=e->next->next; e->next=NULL; shuchu(r); } return 0;}
[解决办法]
- C/C++ code
while(i>0) { q=(struct L*)malloc(sizeof(L)); cin>>q->zhi; p->next=q; //应该是这样,楼主自己悟下,不行我就帮你讲讲,估计很好理解的 p=q; i--; }
[解决办法]