从尾到头打印链表(python)

时间:2023-03-10 04:25:26
从尾到头打印链表(python)

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):###实用python的自动生成
# write code here
if listNode is None:
return []
return self.printListFromTailToHead(listNode.next)+[listNode.val]
#include<iostream>
#include<vector>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
ListNode(int x) :val(x), next(NULL) {};
};
ListNode* CreateListNode(int arr[], int n)
{
ListNode* head;
head = new ListNode(arr[0]);
ListNode* cur;
cur = head;
for (int i = 1; i < n; i++)
{
cur->next = new ListNode(arr[i]);
cur = cur->next;
}
return head;
}
class Solution
{
public:
vector<int>vec;
vector<int> printListFromTailToHead(ListNode* head)
{ if (head == NULL)
return vec;
printListFromTailToHead(head->next);
vec.push_back(head->val);
return vec;
}
};
int main()
{
int n;
scanf("%d", &n);
int i;
int a[100];
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
ListNode* head = CreateListNode(a, n);
/*while (head != NULL)
{
printf("%d ", head->val);
head = head->next;
}*/
vector<int>vec = Solution().printListFromTailToHead(head);
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i]<<" ";
}
system("pause");
return 0;
}