题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
题目分析
题目所提供的的是单向链表,仅有next指针,即仅能从头到尾访问。题目要求从尾到头的顺序返回一个ArrayList,类似于“先进后出”的思维。
解题
普通解法:栈
利用C++的STL中的stack实现该方法。主要步骤为
- 遍历链表将节点值存入stack定义的栈中;
- 访问栈顶元素,存入vector变量,stack变量出栈(C++的stack中
pop()
函数不提供返回值); - 返回vector变量。
代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> v;
stack<int> s;
while(head != NULL){
s.push(head->val);
head = head->next;
}
while(!s.empty()){
v.push_back(s.top());
s.pop();
}
return v;
}
};
递归解法
定义vector全局变量,利用系统的“栈”完成输出。
代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> v;
vector<int> printListFromTailToHead(ListNode* head) {
if(head != NULL){
printListFromTailToHead(head->next);
v.push_back(head->val);
}
return v;
}
};
暴力解法:纯STL
利用C++提供的STL方法暴力解决
代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> v;
while(head != NULL){
v.push_back(head->val);
head = head->next;
}
vector<int>::reverse_iterator riter; //反向迭代器
return vector<int>(v.rbegin(),v.rend());
}
};
以上思路为个人想法和网络各位大佬的题解的结合,欢迎讨论与指正。