1. 知识点
2. 题目
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
示例1
输入
{67,0,24,58}
返回值
[58,24,0,67]
说明:本题目包含复杂数据结构ListNode,点此查看相关信息
3. 实现
3.1 思路
通常,这种情况下,我们不希望修改原链表的结构。返回一个反序的链表,这就是经典的“后进先出”,我们可以使用栈实现这种顺序。每经过一个结点的时候,把该结点放到一个栈中。当遍历完整个链表后,再从栈顶开始逐个输出结点的值,给一个新的链表结构,这样链表就实现了反转。
3.2 实现
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> res;
if(head==nullptr)
return res;
stack<int> nodes;
ListNode* pNode = head;
nodes.push(pNode->val);
while(pNode->next!=nullptr){
pNode = pNode->next;
nodes.push(pNode->val);
}
int top;
while(!nodes.empty()){
top = nodes.top();
res.push_back(top);
nodes.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 listNode:
arraylist = [listNode.val]
while listNode.next:
listNode = listNode.next
arraylist.append(listNode.val)
return arraylist[::-1]
return []
欢迎关注!分享机器学习、深度学习知识点。
知乎:abnercloud