题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
/*
* 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
*
* 思路:
* 1、将链表中每个结点的值压入栈中
* 2、从栈中依次取出栈顶元素并写入整型数组中
*
*
* 输入:
* ListNode 类型链表 0 1 2 3
* 输出:
* vector<int> result is 3210
*/
#include <iostream>
#include <vector>
#include <array>
#include <stack>
using namespace std;
// 声明结构体
struct Node{
int val;
struct Node * next;
Node(int i) :
val(i),next(NULL){
}
};
//输入一个Node链表,输出一个数据翻转的数组
vector<int> printListFromTailToHead(Node* head){
struct Node *pNode = head;
vector<int> node_list;
stack<int> stack_list;
while (pNode!=NULL){
stack_list.push(pNode->val);
pNode = pNode->next;
}
while(!stack_list.empty()){
node_list.push_back(stack_list.top());
stack_list.pop();
}
return node_list;
}
int main(){
struct Node *node_list,*head,*temp;
struct Node node(0);
head = &node;
temp = node_list = head;
//构造Node链表
for (int i = 1; i < 4 ; ++i) {
temp = new Node(i);
node_list->next = temp;
node_list = node_list->next;
}
vector<int> result = printListFromTailToHead(head);
cout << "vector<int> result is " ;
for (int j = 0; j < result.size() ; ++j) {
cout << result[j];
}
cout << endl;
}