反转链表 --剑指offer

题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反正后链表的头结点。

#include<stdio.h>
#include<malloc.h> typedef struct node
{
int Element;
struct node *Link;
}Node; Node *ReverseList(Node *first)
{
Node *NewFirst,*p;
if(first==NULL||first->Link==NULL)
{
return first;
}
NewFirst=first;
while(first->Link!=NULL)
{
p=first->Link;
first->Link=p->Link;
p->Link=NewFirst;
NewFirst=p;
}
return NewFirst; } void main()
{
int i=;
Node *p,*q,*first=NULL;
while(i<)
{
p=(Node*)malloc(sizeof(Node));
p->Element=i;
if(!first)
{
first=p;
first->Link=NULL;
}
else
{
p->Link=first;
first=p;
}
i++;
}
q=first;
while(q)
{
printf("%d,",q->Element);
q=q->Link; }
printf("\n"); p=ReverseList(first);
while(p!=NULL)
{
printf("%d,",p->Element);
p=p->Link;
} }
上一篇:【SRM】518 Nim


下一篇:Hosts简单说明