反转链表

来源:互联网 发布:手机usb共享网络给电脑 编辑:程序博客网 时间:2024/04/29 04:31
#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 nodewhile(cur->next!=NULL){nex=cur->next;cur->next=nex->next;nex->next=head->next;head->next=nex;}return head;}

0 0
原创粉丝点击