SDUTOJ2118 链表逆置

输入多个整数,以-1结束,输出逆置链表




  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <string.h>  
  4. struct node  
  5. {  
  6.     int data;  
  7.     struct node *next;  
  8. }*head;  
  9. int main()  
  10. {  
  11.     struct node *p,*r,*pb,*q;  
  12.     head=(struct node *)malloc(sizeof(struct node));  
  13.     head->next=NULL;  
  14.     p=(struct node *)malloc(sizeof(struct node));  
  15.     pb=(struct node *)malloc(sizeof(struct node));  
  16.     q=(struct node *)malloc(sizeof(struct node));  
  17.     p=head;  
  18.     while(1)  
  19.     {  
  20.         r=(struct node *)malloc(sizeof(struct node));  
  21.         scanf("%d",&r->data);  
  22.         if(r->data==-1)  
  23.             break;  
  24.         p->next=r;;  
  25.         r->next=NULL;  
  26.         p=r;  
  27.     }  
  28.     p=head->next;  
  29.     pb=p->next;  
  30.     while(pb->next!=NULL)  
  31.     {  
  32.         q=pb->next;//记录移动点的下一个  
  33.         pb->next=head->next;//插入到头指针后面  
  34.         head->next=pb;//移动到头指针的下一个  
  35.         p->next=q;//p指针不动,一直是输入的第一个数  
  36.         pb=q;  
  37.     }  
  38.     if(pb->next==NULL)//当链表中只有两个数时  
  39.     {  
  40.         pb->next=head->next;  
  41.         head->next=pb;  
  42.         p->next=NULL;  
  43.     }  
  44.     //输出  
  45.     p=head->next;  
  46.     while(p!=NULL)  
  47.     {  
  48.         printf("%d",p->data);  
  49.         if(p->next!=NULL)  
  50.             printf(" ");  
  51.         p=p->next;  
  52.     }  
  53.     return 0;  
  54. }  
  55.    
  56.   
  57.   

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值