2118=数据结构实验之链表三:链表的逆置

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 struct node
 4 {
 5     int data;
 6     struct node*next;
 7 };
 8 int main()
 9 {
10     int n,i;
11     struct node*head,*p,*end,*q;
12     head=(struct node*)malloc(sizeof(struct node));//为head在这个链表中开辟一个空间。
13     head->next=NULL;//一个链表要有结尾。
14     end=head;
15    while(1)
16     {
17         p=(struct node*)malloc(sizeof(struct node));
18         scanf("%d",&p->data);
19         if(p->data==-1)break;
20         p->next=NULL;
21         end->next=p;
22         end=p;
23 
24     }
25     p=head->next;
26     head->next=NULL;
27     q=p->next;
28     while(p)
29     {
30         p->next=head->next;//利用P来做一个储存点。
31         head->next=p;
32         p=q;
33         if(q!=NULL)
34         {
35             q=q->next;//最后NULL也会出现在链表内,因为链表要有结束点。
36         }
37     }
38     for(p=head->next;p;p=p->next)
39     {
40 
41         printf("%d",p->data);
42         if(p->next!=NULL)printf(" ");
43     }
44     return 0;
45 }

 

posted @ 2019-02-25 16:34  念文丶  阅读(383)  评论(0编辑  收藏  举报