单向链表的创建和逆转(完整程序)

自己没事了随便写的,仅做参考!不好的地方麻烦指出。吐舌头

友情提示:如果要拷贝这段代码,可以点击代码上方的很小的字--view plain,(不知道你看见没?)然后再全部选中之后再复制。如果直接复制会把左边的行号也复制进去。

#include <stdio.h> #include <malloc.h> typedef struct test { int a; struct test *next; }lianbiao; lianbiao* create()//创建链表 { lianbiao *head,*temp; int i; printf("请输入一些整数,以0结束:"); temp=head=(lianbiao *)malloc(sizeof(lianbiao)); scanf("%d",&i); if(i==0) { printf("you input zero!exit now!"); return head; } head->a=i; head->next=NULL; while(1) { scanf("%d",&i); if(i==0) break; else { temp->next=(lianbiao *)malloc(sizeof(lianbiao)); temp=temp->next; temp->a=i; temp->next=NULL; } } return head; } lianbiao* reverse(lianbiao *p)//逆转链表 { lianbiao *temp1,*temp2; if(p->next==NULL) { printf("链表节点数小于2,无法逆转!\n"); return p; } int flag=0; while(p->next!=NULL) { if(flag==0) { temp1=p; temp2=p->next; p->next=NULL; p=temp2; flag=1; continue; } temp2=p->next; p->next=temp1; temp1=p; p=temp2; } p->next=temp1;//将原链表的末尾节点指向倒数第二个节点 return p; } void print(lianbiao *p) { while(p->next!=NULL) { printf("%d ",p->a); p=p->next; } printf("%d ",p->a); printf("\n"); } int main() { lianbiao *temp; temp=create(); print(temp);//打印出原链表 print(reverse(temp));//打印出逆转后的链表 return 0; }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值