#include<iostream>
#include<cstdio>
//#include<algorithm>
using namespace std;
const int N=10;
//head表示头结点的下标
//e[i]表示节点i的值
//ne[i]表示节点i的next指针
//idx表示用到了哪个地址,就是下标
int head= -1,e[N],ne[N],idx;
void add_to_head(int x)
{
e[idx]=x;
ne[idx]=head;
head=idx++;
}
int main()
{
int val;
while(scanf("%d",&val) != EOF) //~scanf表示没有输入值的时候,结束while循环
{
add_to_head(val);
}
for(int i=head;i!=-1;i=ne[i])
cout<<e[i]<<" ";
cout<<endl;
return 0;
}
供参考:
#include<iostream>
#include<cstdio>
//#include<algorithm>
using namespace std;
const int N = 10;
//head表示头结点的下标
//e[i]表示节点i的值
//ne[i]表示节点i的next指针
//idx表示用到了哪个地址,就是下标
int head = -1, e[N], ne[N], idx = 0;
void add_to_head(int x)
{
e[idx] = x;
ne[idx] = head;
head = idx++;
}
int main()
{
int val;
while (cin>>val) //ctrl + z
{
add_to_head(val);
}
for (int i = head; i != -1; i = ne[i])
cout << e[i] << " ";
cout << endl;
return 0;
}
//1 2 3 4 5 ^ Z
//e[0] = 1, head = 0, ne[0] = -1
//e[1] = 2, head = 1, ne[1] = 0
//e[2] = 3, head = 2, ne[2] = 1
//e[3] = 4, head = 3, ne[3] = 2
//e[4] = 5, head = 4, ne[4] = 3
//5 4 3 2 1
//请按任意键继续. . .
是输出了5 4 3 2 1啊,难道你输出不是吗?
idx 的初值没有