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

数据结构实验之链表三:链表的逆置
Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description
输入多个整数,以-1作为结束标志,顺序建立一个带头结点的单链表,之后对该单链表的数据进行逆置,并输出逆置后的单链表数据。
Input
输入多个整数,以-1作为结束标志。
Output
输出逆置后的单链表数据。
Sample Input
12 56 4 6 55 15 33 62 -1
Sample Output
62 33 15 55 6 4 56 12
Hint
不得使用数组。
Source
//先用顺序建立一个链表,然后再用逆序按着顺序的data建立一个逆表,输出逆表,当然如果你不喜欢这么做
//还可以建立双向链表,直接反向输出就行,这里就不给出代码了

#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
}*h,h1,t,q;
int main()
{
h=(struct node
)malloc(sizeof(struct node));
h->next=NULL;
t=h;
int w;
while (scanf("%d",&w)!=EOF) //输入数
{
if(w==-1)break;
else
{
q=(struct node
)malloc(sizeof(struct node));//顺序建立链表
q->data=w;
q->next=NULL;
t->next=q;
t=q;
}
}
h1=(struct node
)malloc(sizeof(struct node));
h1->next=NULL;
while(h->next!=NULL) //逆向在按着刚刚建的顺序链表再建立一个逆向的
{
h=h->next;
q=(struct node *)malloc(sizeof(struct node));
q->data=h->data;
q->next=h1->next;
h1->next=q;
}
q=h1->next;
printf("%d",q->data); //输出
while(q->next!=NULL)
{
q=q->next;
printf(" %d",q->data);
}
printf("\n");
return 0;
}

发布了37 篇原创文章 · 获赞 3 · 访问量 718

猜你喜欢

转载自blog.csdn.net/Are_you_ready/article/details/104704781