输入多个整数,以-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;
- }
本文介绍了一个简单的链表逆置程序实现过程。通过输入一系列整数构建链表,并使用C语言实现链表的逆置操作。该程序首先构建原始链表,然后通过迭代方式将链表逆置,最后输出逆置后的链表元素。
1342

被折叠的 条评论
为什么被折叠?



