题目描述:
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
注:本系列均在牛客网的剑指Offer在线测试调试通过,并且在VS2015中编译通过;
代码如下所示:
#include<stack>
#include<vector>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> Result;
if (head == nullptr) return Result;
stack<ListNode*> Reverse_node;
ListNode *node = head;
while (node != NULL) {
Reverse_node.push(node);
node = node->next;
}
while (!Reverse_node.empty()) {
node = Reverse_node.top();
Result.push_back(node->val);
Reverse_node.pop();
}
return Result;
}
};
int main(int argc, char** argv) {
Solution test;
ListNode test_(12);
ListNode test_1(21);
ListNode test_2(32);
ListNode test_3(44);
test_.next = &test_1;
test_1.next = &test_2;
test_2.next = &test_3;
test.printListFromTailToHead(&test_);
system("pause");
return 0;
}