题目描述
输入一个链表,从尾到头打印链表每个节点的值。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
思路一
/**
* 思路一:从头到尾遍历链表,顺序插入vector,然后翻转vector
* 运行时间:0ms
* 占用内存:8552k
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> org;
while(head != NULL){
org.push_back(head->val);
head = head->next;
}
reverse(org.begin(),org.end());
return org;
}
};
思路二
/**
* 思路二:从头到尾遍历链表,插入vector,每个元素都插入到vector前面
* 运行时间:0ms
* 占用内存:8552k
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> org;
while(head != NULL){
org.insert(org.begin(),head->val);
head = head->next;
}
return org;
}
};