链表有关问题,居然断炼了.
链表问题,居然断炼了....
------解决方案--------------------
- 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。 */ /* 当k=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)); cin>>q->zhi; p->next=q; p=q; i--; } p->next=NULL; e=r; shuchu(e); cout<<endl; 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; } /* 当k=5时会出现断链的现象,只会输出前两个数据 */ if(k==5) { //r为头结点,e第二个节点,t第三个,q第四个,p第五个 e=r->next; t=e->next; //第一次变序 p->next=t; t->next=NULL; e->next=q; //变序后 r第一个节点,e第二个,q第三个,p第四个,t最后一个节点 //第二次变续 r->next=p; t->next=e; q->next=NULL; shuchu(r); } /* 这题我想出另一个方法,当k=5时,让r、e、t、q、p分别标记5个节点, 原序列为r、e、t、q、p。第一次变序就成为r、e、q、p、t。 第二次变序就成为 r、p、t、e、q。那么就直接按第二次的顺序一个一个输出. 这种方法行不行 */ return 0; }
------解决方案--------------------
- C/C++ code
p->next=t; t->next=NULL; e->next=q; .......