ReseverLink

来源:互联网 发布:淘宝直通车有用吗 编辑:程序博客网 时间:2024/06/06 04:58
#include<stdio.h>#include<stdlib.h>typedef struct LinkNode{int val;LinkNode* next;}*LinkList;//不带头结点LinkNode* CreateLink(int n){LinkList l=NULL;;if(n<=0){printf("链表为空\n");return NULL;}l=(LinkNode*)malloc(sizeof(LinkNode));if(!l){printf("overflow!");exit(1);}printf("请输入结点的值\n");scanf("%d",&l->val);l->next=NULL;LinkNode *p,*q;q=l;for(int i=1;i<n;i++){p=(LinkNode*)malloc(sizeof(LinkNode));    if(!l){printf("overflow!");exit(1);    }    printf("请输入结点的值\n");    scanf("%d",&p->val);p->next=q->next;q->next=p;q=p;}return l;}//k 为位序LinkNode* FindKthtoTail(LinkList l,unsigned int k){if(l==NULL || k==0){return NULL;}int i,j;LinkNode *p,*q;p=l;//走到第k个for(i=1;i<k;i++){p=p->next;if(p==NULL){printf("链表不足k个\n");exit(1);}}q=l;while(p->next){p=p->next;q=q->next;}return q;}LinkNode* ReverseLink(LinkNode *l){if(l==NULL){printf("链表为空\n");return NULL;}LinkNode *pre,*next,*p,*reverseHead;p=l;pre=NULL;while(p){next=p->next;if(next==NULL)reverseHead=p;p->next=pre;pre=p;p=next;}return reverseHead;}void Print(LinkList l){if(l==NULL){printf("链表为空\n");return;}LinkNode* p;p=l;while(p){printf("%3d",p->val);p=p->next;}}void main(){int n;printf("请输入结点的个数\n");scanf("%d",&n);LinkList l;l=CreateLink(n);l=ReverseLink(l);Print(l);}

0 0
原创粉丝点击