一、题目
二、解法
- 对于该题,我首先想到的是利用栈的数据结构。由于遍历链表只能顺序进行,那可以不断将节点的值压入栈中,遍历完成后,将栈顶元素添加到数组中,并进行出栈操作(即删除栈顶元素)。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
#include <vector>
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> stk;
vector<int> res;
while (head!=nullptr){
stk.push(head->val);
head = head->next;
}
while (!stk.empty()){
res.emplace_back(stk.top());
stk.pop();
}
return res;
}
};
- 递归算法的底层实现其实也利用了栈这种数据结构,也就是说,递归在不断递下去的过程中,需要保存函数的参数,变量等,即需要入栈,而到达边界条件以后,需要不断返回到上一级问题,即需要出栈。那么该问题也可以采用递归算法:
1)确定非边界条件:可以这么考虑,从头节点开始,不断遍历到尾结点,将head作为递归函数的参数,不断递下去,不做任何操作;
2)边界条件:遍历到尾节点时,即head为空时,直接退出递归函数,
到达边界条件以后,就可以将尾结点的值添加到数组中。
python代码:
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param listNode ListNode类
# @return int整型一维数组
#
import sys
"""设置递归深度,python中递归深度是有限制的。一般默认为999,当超过999时,会出现错误:
RuntimeError: maximum recursion depth exceeded while calling a Python object"""
sys.setrecursionlimit(100000)
class Solution:
def reverse_list(self, head: ListNode, res: List[int]):
if (head != None):
res = self.reverse_list(head.next, res)
res.append(head.val)
return res
def printListFromTailToHead(self , listNode: ListNode) -> List[int]:
# write code here
res = []
res = self.reverse_list(listNode, res)
return res
C++代码:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
//递归函数
void recursion(ListNode* head, vector<int>& res){
if(head != NULL){
//先往链表深处遍历
recursion(head->next, res);
//再填充到数组就是逆序
res.push_back(head->val);
}
}
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
//递归函数打印
recursion(head, res);
return res;
}
};