洛谷 U228721:反转单链表
·
【题目来源】
https://www.luogu.com.cn/problem/U228721
【题目描述】
题目给出一串数字,首先,你需要把这些数字构造成一个单链表,然后将此单链表反转。
【输入格式】
一行,一串数字。
【输出格式】
一行,一串数字,空格分隔。
【输入样例】
1 2 3
【输出样例】
3 2 1 None
【说明/提示】
注意,本题要求答案最后加上None哦。
【算法分析】
● 单链表的相关代码,若借助示意图来写,会更容易。
● 若有两个指针 a 与 b,且 a=b,则表示 a 指向 b 指向的结点。这一点对快速绘制单链表的示意图有很多帮助。
【算法代码一】
本代码由于用到 while(cin>>x),所以在输入完样例 1 2 3 后,需要按回车键,然后再按下 Ctrl+Z 键,才能看到运行结果 3 2 1 None。
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
int e[maxn],ne[maxn],idx,h=-1;
void add(int x) {
e[idx]=x,ne[idx]=h,h=idx++;
}
int main() {
int x;
while(cin>>x) {
add(x);
}
for(int i=h; i!=-1; i=ne[i]) {
cout<<e[i]<<" ";
}
cout<<"None"<<endl;
return 0;
}
/*
in:
5
6 3 9 2 1
out:
1 2 9 3 6 None
*/
【算法代码二】
#include<bits/stdc++.h>
using namespace std;
struct LNode {
int data;
LNode *next;
};
int main () {
LNode *L=new LNode;
L->next=NULL;
int x;
while(cin>>x) {
LNode *p;
p=new LNode;
p->data=x;
p->next=L->next;
L->next=p;
}
while(L->next) {
cout<<L->next->data<<" ";
L->next=L->next->next;
}
cout<<"None"<<endl;
return 0;
}
/*
in:
1 2 3
out:
3 2 1 None
*/
【算法代码三】
#include <bits/stdc++.h>
using namespace std;
vector<int> v;
int main() {
int x;
while(cin>>x) {
v.push_back(x);
}
for(int i=v.size()-1; i>=0; i--) {
cout<<v[i]<<" ";
}
cout<<"None";
return 0;
}
/*
in:
1 2 3
out:
3 2 1 None
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/108586756
更多推荐


所有评论(0)