欢迎来到IT嘟嘟的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。
扩大
缩小

从尾到头打印链表(python/c++)

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个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;
}

  

 

posted on 2019-02-25 15:45  IT嘟嘟  阅读(145)  评论(0编辑  收藏  举报

导航