题目描述
根据一个整数序列构造一个单链表,然后将其反转。
例如:原单链表为 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
分析:
本题的链表逆转采用类似头插法的策略,首先找到第一个元素和最后一个元素,然后将这个元素插到原本最后一个元素之后,然后找到第二元素,并不断重复这个方法,直到第一个元素和原本最后一个元素重叠。
#include <iostream>
using namespace std;
struct node{
int data;
node* next;
};
struct linklist{
node* head, *rear;
};
void createList(linklist &L){
L.head = new node;
L.head -> next = NULL;
L.rear = L.head;
}
void RearNewNode(linklist &L, int e){
node* s = new node;
s -> data = e;
s -> next = NULL;
L.rear -> next = s;
L.rear = s;
}
void FrontNewNode(linklist &L, int e){
node *s = new node;
s -> data = e;
s -> next = L.head -> next;
if(L.head -> next){
L.rear = s;
}
L.head -> next = s;
}
void PrintList(linklist L){
node* p = L.head -> next;
while(p){
cout << p -> data;
if(p -> next){
cout << ' ';
}else{
cout << '\n';
}
p = p -> next;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n;
while(cin >> n){
if(n == 0){
cout << "list is empty\n";
continue;
}
linklist L;
createList(L);
for(int i = 0; i < n; i++){
int e;
cin >> e;
RearNewNode(L, e);
}
PrintList(L);
node* p = L.head -> next;
node* q = L.rear;
while(p != q){
if(q -> next){
L.rear = p;
}
L.head -> next = p ->next;
p -> next = q -> next;
q -> next = p;
p = L.head -> next;
}
PrintList(L);
}
return 0;
}