【题目来源】
https://www.acwing.com/problem/content/18/
【题目描述】
输入一个链表的头结点,按照从尾到头的顺序返回节点的值。
返回的结果用数组存储。
【数据范围】
0≤ 链表长度 ≤1000 。
【测试样例】
输入:[2, 3, 5]
返回:[5, 3, 2]
【算法代码】
数组模拟单链表的头插法。单链表的头插法可实现输入的逆序输出。
数组模拟单链表:https://blog.csdn.net/hnjzsyjyj/article/details/132185463
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+5;
// head 头结点的下标
// e[i] 结点i的值
// ne[i] 结点i的next指针
// idx 当前可用结点的下标,可看做指针
int head, e[N], ne[N], idx;
void init() { //初始化
head=-1; //head指向空
idx=0;
}
void add_to_head(int x) { //将x插入到首元结点
e[idx]=x;
ne[idx]=head; // idx指向head指向的结点
head=idx++; // head指向idx
}
int main() {
int n;
cin>>n;
init(); // very important
while(n--) {
int x;
cin>>x;
add_to_head(x);
}
for(int i=head; i!=-1; i=ne[i]) cout<<e[i]<<" ";
return 0;
}
/*
in:
5
6 3 9 2 1
out:
1 2 9 3 6
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/132185463
https://www.acwing.com/solution/content/129371/