06 从尾到头打印链表
题目
输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
C++ 题解
方法一
使用递归实现:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> res;
vector<int> printListFromTailToHead(ListNode* head)
{
if(head != nullptr)
{
if(head->next != nullptr)
{
res = printListFromTailToHead(head->next);
}
res.push_back(head->val);
}
return res;
}
};
方法二
使用反向迭代器:
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> v;
ListNode *p = head;
while (p != nullptr) {
v.push_back(p->val);
p = p->next;
}
//反向迭代器创建临时对象
return vector<int>(v.rbegin(), v.rend());
}
};
方法三
使用栈实现:
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> res;
stack<int> s;
while(head != nullptr)
{
s.push(head->val);
head = head->next;
}
while(!s.empty())
{
res.push_back(s.top());
s.pop();
}
return res;
}
};
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 not listNode:
return []
res = []
while listNode.next is not None:
res.append(listNode.val)
listNode = listNode.next
res.append(listNode.val)
return res[::-1]