SDUT-2118_数据结构实验之链表三:链表的逆置

时间:2023-03-10 02:25:59
SDUT-2118_数据结构实验之链表三:链表的逆置

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

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

不得使用数组。

跟链表的插入差不多,将节点断开重新插入到头结点后面。

#include <stdio.h>
#include <string.h>
#include <stdlib.h> typedef struct node
{
int data;
struct node *next;
}link; link *newlink()
{
link *t;
t = (link*)malloc(sizeof(link));
t->next = NULL;
return t;
} link *create()
{
link *head,*p,*q;
int x;
head = newlink();
p = head;
while(scanf("%d",&x))
{
if(x==-1)
break;
q = newlink();
q->data = x;
q->next = NULL;
p->next = q;
p = q;
}
return head;
} link *change(link *head)
{
link *p,*q;
p = head->next;
head->next = NULL;
while(p)
{
q = p;
p = p->next;
q->next = head->next;
head->next = q;
}
return head;
} void show(link *head)
{
link *p;
p = head->next;
while(p)
{
if(p->next==NULL)
printf("%d\n",p->data);
else
printf("%d ",p->data);
p = p->next;
}
} int main()
{
link *head;
head = create();
head = change(head);
show(head);
return 0;
}