您的位置:首页 > 其它

链表的逆序

2007-11-27 17:11 253 查看
今天看了一道题,要求是将一个链表逆序,经过调试,终于成功,源代码如下:

#include <stdio.h>

struct node
{
int num;
char *name;
struct node *next;
};

struct node * ni(struct node *ptr)
{
struct node *q,*p,*r,*s;
s=ptr;
if(ptr==NULL)
{
printf("the lian is null/n");
}
else
{
p=ptr;
q=p->next;
r=q->next;
while(r!=NULL)
{
q->next=p;
p=q;
q=r;
r=r->next;
}
q->next=p;
ptr=q;
s->next=NULL;
return ptr;
}
}

print(struct node * pp)
{
struct node *qq;
qq=pp;
if(qq==NULL)
printf("nothing to print/n");
else
while(qq!=NULL)
{
printf("%d/t%s/n",qq->num,qq->name);
qq=qq->next;
}
}

main()
{
struct node n1,n2,n3,n4,*head,*h;
n1.num=1;
n1.name="lilei";
head=&n1;
n1.next=&n2;
n2.num=2;
n2.name="wang";
n2.next=&n3;
n3.num=3;
n3.name="zhang";
n3.next=&n4;
n4.num=4;
n4.name="zhao";
n4.next=NULL;
print(head);
h=ni(head);
print(h);
}

现说下编码过程中遇到的错误,主要是在函数struct node * ni(struct node *ptr)中的while循环中while(q!=NULL)
{
q->next=p;
p=q;
q=r;
r=r->next;
}

这样处理了,这样处理的错误是最后r已经为空,但还是执行 r=r->next; 造成了段错误。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: