SDUTOJ2118 链表逆置

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




  1. #include   
  2. #include   
  3. #include   
  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.   

你可能感兴趣的:(链表)