题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
思路过程
- 依次遍历链表节点,取出节点的值
- 新增一个数组,将节点的值,从尾到头放入:第一个节点的值,放在最末尾,第二节点的值放在倒数第二,以此类推…
- 如果是双向链表,或者单向循环链表 如何实现?
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
ret_list=[]
while listNode:
ret_list.insert(0,listNode.val)
listNode=listNode.next
return ret_list
# 实例测试一下
class Node(object):
def __init__(self, item):
self.item = item
self.next = None
def print_link(node):
while node: # while node is not None: 或者 while node != None:
print(node.item)
node = node.next
def reverse_link(node):
ret_list = []
while node:
ret_list.insert(0,node.item)
node = node.next
return ret_list
if __name__ == '__main__':
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n1.next = n2
n2.next = n3
# n3.next = None
# print_link(n1)
print(reverse_link(n1)) # [3, 2, 1]