目录
题目
输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。
如输入{1,2,3}的链表如下图:
返回一个数组为[3,2,1]
0 <= 链表长度 <= 10000
示例1
输入:
{1,2,3}
返回值:
[3,2,1]
示例2
输入:
{67,0,24,58}
返回值:
[58,24,0,67]
代码
#include<iostream>
#include<vector>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* Create(int n)
{
Node* p, * h, * s;
h = new Node;
h->next = NULL;
p = h;
for (int i = 0; i < n; i++)
{
s = new Node;
cin >> s->data;
p->next = s;
p = s;
}
p->next = NULL;
return h;
}
void Print(Node* h)
{
Node* p = h->next;
while (p != NULL)
{
cout << p->data << "\t";
p = p->next;
}
cout << endl;
}
vector<int>reverse(Node* h)
{
Node* p = h->next;
vector<int> ans;
while (p != NULL)
{
ans.push_back(p->data);
p = p->next;
}
reverse(ans.begin(), ans.end());
for (vector<int>::iterator it = ans.begin(); it != ans.end(); it++)
{
cout << *it << "\t";
}
cout << endl;
return ans;
}
int main()
{
Node* head = new Node;
head->next = NULL;
int i;
cout << "请输入单链表的个数:";
cin >> i;
cout << "请输入反转之前的链表结点:";
head = Create(i);
cout << "反转之后的链表结点是:";
reverse(head);
return 0;
}
运行结果:
知识点
1.STL容器——vector以及reverse操作,STL容器的打印要依靠迭代器
for (vector<int>::iterator it = ans.begin(); it != ans.end(); it++)
{
cout << *it << "\t";
}