#include<stdio.h>
#include<malloc.h>
typedef struct LNode{
int num;
struct LNode * next;
}LNode,*LinkList;
LinkList linkreverse(LinkList );
LinkList reverse(LinkList);
int main(){
LinkList a,b,c,d,head;
head=(LinkList)malloc(sizeof(LNode));
a=(LinkList)malloc(sizeof(LNode));
b=(LinkList)malloc(sizeof(LNode));
c=(LinkList)malloc(sizeof(LNode));
d=(LinkList)malloc(sizeof(LNode));
a->num=1;a->next=b;
b->num=2;b->next=c;
c->num=3;c->next=d;
d->num=4;d->next=NULL;
head->next=a;
//------print the link---------
/* LinkList p;
p=head->next;
while(p){
printf("%d ",p->num);
p=p->next;
}
printf("\n");*/
head=reverse(head);
//------print the link---------
LinkList p;
p=head->next;
while(p){
printf("%d ",p->num);
p=p->next;
}
printf("\n");
return 0;
}
LinkList linkreverse(LinkList head){
if(head==NULL)
return NULL;
LinkList pre,cur,nex;
cur=head->next;
pre=NULL;
while(cur){
nex=cur->next;
cur->next=pre;
pre=cur;
cur=nex;
}
head->next=pre;
return head;
}
LinkList reverse(LinkList head){
if(head==NULL||head->next==NULL)
return NULL;
LinkList cur,nex;
cur=head->next;//point to the first node
while(cur->next!=NULL){
nex=cur->next;
cur->next=nex->next;
nex->next=head->next;
head->next=nex;
}
return head;
}
反转链表
最新推荐文章于 2024-07-10 17:20:30 发布