描述
输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。
如输入{1,2,3}的链表如下图:
返回一个数组为[3,2,1],0<=链表长度<=10000
我的解答:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> a;
stack<int> s;
for(head;head!=nullptr;head=head->next){
s.push(head->val);
}
for(s;!s.empty();s.pop()){
cout<<s.top();
a.push_back(s.top());
}
return a;
}
};
可以看出我的结果并不是很好,因为我首先将链表保存到了一个stack中,然后再将stack中的数据保存到结果的vector中。因为这个是让反向传输,所以我用堆栈进行了转换。
标准解答:
题目中给出了一种简单粗暴的解答方法,直接采用reverse函数(这个函数是C++中提出的,在C中没有,可以用来转换vector,string等,需要包含头文件:#include<algorithm>,其用来反转[first,last)的数据。)
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ans;
// 从头节点开始进行遍历
while(head){
// 将每个节点的权值放入动态数组里面
ans.push_back(head->val);
// 指针后移动
head=head->next;
}
// 反转整个数组
reverse(ans.begin(),ans.end());
return ans;
}
};
可以看到时间会提升一点点,但是其实复杂度还是O(n);O(n)
(如果有更好的方法,感谢讨论~)