输入多个整数,以-1结束,输出逆置链表
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct node
- {
- int data;
- struct node *next;
- }*head;
- int main()
- {
- struct node *p,*r,*pb,*q;
- head=(struct node *)malloc(sizeof(struct node));
- head->next=NULL;
- p=(struct node *)malloc(sizeof(struct node));
- pb=(struct node *)malloc(sizeof(struct node));
- q=(struct node *)malloc(sizeof(struct node));
- p=head;
- while(1)
- {
- r=(struct node *)malloc(sizeof(struct node));
- scanf("%d",&r->data);
- if(r->data==-1)
- break;
- p->next=r;;
- r->next=NULL;
- p=r;
- }
- p=head->next;
- pb=p->next;
- while(pb->next!=NULL)
- {
- q=pb->next;//记录移动点的下一个
- pb->next=head->next;//插入到头指针后面
- head->next=pb;//移动到头指针的下一个
- p->next=q;//p指针不动,一直是输入的第一个数
- pb=q;
- }
- if(pb->next==NULL)//当链表中只有两个数时
- {
- pb->next=head->next;
- head->next=pb;
- p->next=NULL;
- }
- //输出
- p=head->next;
- while(p!=NULL)
- {
- printf("%d",p->data);
- if(p->next!=NULL)
- printf(" ");
- p=p->next;
- }
- return 0;
- }