题目描述
根据一个整数序列构造一个单链表,然后将其反转。
例如:原单链表为 2 3 4 5 ,反转之后为5 4 3 2
输入
输入包括多组测试数据,每组测试数据占一行,第一个为大于等于0的整数n,表示该单链表的长度,后面跟着n个整数,表示链表的每一个元素。整数之间用空格隔开
输出
针对每组测试数据,输出包括两行,分别是反转前和反转后的链表元素,用空格隔开
如果链表为空,则只输出一行,list is empty
样例输入 Copy
5 1 2 3 4 5
0
样例输出 Copy
1 2 3 4 5
5 4 3 2 1
list is empty
#include<bits/stdc++.h>
using namespace std;
struct node
{
int val;
struct node *next;
node(int x): val(x), next(nullptr){}
};
int main()
{
int n, a;
while(cin >> n)
{
if(n==0)
cout<< "list is empty" << endl;
else
{
struct node *head = new node(0);
struct node *p = head;
while(n--) // 将输入的元素构建成单链表
{
cin >> a;
struct node *last = new node(a);
p->next = last;
p = last;
}
p = head->next;
while(p && p->next) // 输出单链表
{
cout << p->val << " ";
p = p->next;
}
cout << p->val << endl;
p = head->next; // 翻转单链表
struct node *h = new node(0);
while(p)
{
head->next = head->next->next;
p->next = h->next;
h->next = p;
p=head->next;
}
delete head;
struct node *index = h->next; // 输出翻转后的单链表
while(index && index->next)
{
cout << index->val << " " ;
index = index->next;
}
cout << index->val << endl;
}
}
return 0;
}