题目描述
根据一个整数序列构造一个单链表,然后将其反转。
例如:原单链表为 2 3 4 5 ,反转之后为5 4 3 2
输入
输入包括多组测试数据,每组测试数据占一行,第一个为大于等于0的整数n,表示该单链表的长度,后面跟着n个整数,表示链表的每一个元素。整数之间用空格隔开
输出
针对每组测试数据,输出包括两行,分别是反转前和反转后的链表元素,用空格隔开
如果链表为空,则只输出一行,list is empty
样例输入
5 1 2 3 4 5
0
样例输出
1 2 3 4 5
5 4 3 2 1
list is empty
反转图示:点击这里
- 先尾插法建立单链表
- 然后断开头结点与第一个元素结点的连接,用临时指针指向第一个元素.
- 采用头插法重新建表.
这道题目需要注意的一点小细节就是输出list is empty的时候没有换行,否则会出现输出超限60%.
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
/*
单链表反转图示:https://blog.csdn.net/blioo/article/details/62050967
*/
using namespace std;
struct node
{
int data;
node *next;
};
int main()
{
int n;
while(~scanf("%d",&n))
{
if(n==0)
{
printf("list is empty");
break;
}
node *head, *now, *p;
head = new node;
head->next = NULL;
p = head;
int t;
for(int i=0; i<n; i++)//建表
{
scanf("%d",&t);
printf("%d ", t);
now = new node;
now->data = t;
now->next = NULL;
p->next = now;
p = now;
}
printf("\n");
p = head->next;
head->next = NULL;
while(p!=NULL)//头插法建表
{
node *temp = new node;
temp->data = p->data;
temp->next = head->next;
head->next = temp;
p = p->next;
}
node *m = head->next;
m = head->next;
while(m!=NULL)
{
printf("%d", m->data);
if(m->next!=NULL)
printf(" ");
else
printf("\n");
m = m->next;
}
// printf("aa");
}
return 0;
}