时空要求
- 时间限制:1秒
- 空间限制:32768K
- 热度指数:712397
- 本题知识点: 链表
题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
解题思路
优先选用递归法。
思路一: 递归法
python实现
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
if listNode is None:
return []
return self.printListFromTailToHead(listNode.next) + [listNode.val]
思路二:直接存下来再逆序
遍历一遍链表把所有值存到数组中,最后再对数组中元素逆序。时间复杂度和空间复杂度都为为O(n).
c++实现
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> temp;
ListNode* p=head;
int length=0;
while(p!=NULL){
length++;
p=p->next;
}
temp.resize(length);
p=head;
for(int i=0; i<length; i++){
temp[length-1-i]=p->val;
p=p->next;
}
return temp;
}
};
- 运行时间:3ms
- 占用内存:492k
思路三:用栈存储再弹出
时间复杂度和空间复杂度都为O(n).