首先贴正确的代码
#include"iostream"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct node
{
int x;
node *next;
}nodex;
int charu(nodex *root,int cmp);
void fanzhi(nodex **root);
int main()
{
nodex* root=(nodex*)malloc(sizeof(nodex));
root->x=8;
root->next=NULL;
for(int i=0;i<8;i++)
charu(root,i);
nodex *p=root;
while(p)
{cout<<p->x;
p=p->next;
}
cout<<'\n';
fanzhi(&root);
p=root;
while(p)
{cout<<p->x;
p=p->next;
}
}
int charu(nodex *root,int cmp)//头插法
{
nodex* q=(nodex*)malloc(sizeof(nodex));
q->x=cmp;
q->next=root->next;
root->next=q;
return 0;
}
void fanzhi(nodex **root)
{
nodex *pre=*root;
nodex *now=(*root)->next;
(*root)->next=NULL;
while(now)
{
nodex *pre_tmp=pre;
nodex *now_tmp=now;
pre=now;
now=now->next;
now_tmp->next=pre_tmp;
}
*root=pre; }
想了想思路,就按着自己的思路写。。。不写不知道,一写吓一跳,这么简单地问题都难道我了,悲剧啊!!!!!! fanzhi()函数中首先写的是
while(now)
{
nodex *pre_tmp=pre;
nodex *now_tmp=now;
pre=pre->next;
now=now->next;
now_tmp->next=pre_tmp;
}
pre一下子成死循环了。
下来搞定pre了,接着刚开始的fanzhi函数是这么定义的:void fanzhi(nodex *root)
估计还有的人没注意这点:传进来的其实只是一个数,改变root的值根本不能改变root中存储的地址数要想改变root中存储的地址数,
只能这样nodex **root,传进去的是指向root的指针,*root其实就是root中存储的地址数。所以就能修改root的值了。