从尾到头打印链表(python)
2024-09-13 13:14:23
题目描述
输入一个链表,按链表值从尾到头的顺序返回一个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;
}
最新文章
- Oracle数据库操作知道
- 背水一战 Windows 10 (37) - 控件(弹出类): MessageDialog, ContentDialog
- [C#解惑] #1 在构造函数内调用虚方法
- 使用PreApplicationStartMethodAttribute
- PHP-----类与对象,成员方法,成员属性,构造方法,析构方法
- 讲述一下自己在linux中配置ftp服务的经历
- css 描述css reset的作用和用途。
- BZOJ 2111 排列计数
- sharepoint 2010 切换域
- node-odata: ASP.NET WEB API OData的替代品
- Qt之进程间通信(Windows消息)
- statusBar显示白色字体
- SQL Express几个版本的区别
- jQuery选择器实现隔行变色和使用javaScript实现隔行变色
- angularJS Directive学习
- C语言使用HZK16显示每个像素的代码
- .NET CORE学习笔记系列(3)——ASP.NET CORE多环境标识
- # 20175333曹雅坤《Java程序设计》第1周学习总结
- 12款 JavaScript 表格控件(DataGrid)
- Android开发 ---实现ListView的A-Z字母排序和过滤搜索功能