题目描述
按数字输入顺序创建单链表。不可借助数组、容器,不可开辟新结点空间。编写函数,在原链表上实现单链表的反转。例如单链表10->20->30,反转后变为单链表30->20->10。
注:不符合题目要求,使用上题逆序输出不计分。
输入
测试次数t
每组测试数据一行,格式如下:
数据个数n,后跟n个整数
输出
对每组测试数据,输出反转后的单链表。
示例输入
2
10 1 2 3 4 5 6 7 8 9 10
4 19 20 15 -10
示例输出1
10 9 8 7 6 5 4 3 2 1
-10 15 20 19
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node* next;
int flag;
public:
Node(){
next=NULL;
}
void init(){
cin>>data;
}
};
void set_(Node*&head,int n){
Node* p1,*p2,*p3;
p1=head->next;
p2=p1->next;
p1->next=NULL;
if(n<=1) return;
p3=p2->next;
for(int i=1;i<n;i++){
//head->next=p2;
p2->next=p1;
p1=p2;
p2=p3;
if(p3==NULL) break;
else p3=p3->next;
}
head->next=p1;
}
void display(Node* p){
while(p->next->next){
cout<<p->next->data<<" ";
p=p->next;
}
cout<<p->next->data<<" "<<endl;
}
int main(){
int t;
cin>>t;
while(t--){
Node* head=new Node;
int i,n;
cin>>n;
Node* p1=head;
for(i=0;i<n;i++){
p1->next=new Node;
p1->next->init();
p1=p1->next;
}
set_(head,n);
display(head);
}
}