"""
title:面试题06。 从尾到头打印节点
introduction:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
"""
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = next
class List:
def __init__(self):
self.head = None
def add(self, val):
if self.head is None:
self.head = ListNode(val)
return
p = self.head
while p.next is not None:
p = p.next
p.next = ListNode(val)
def printall(self):
p = self.head
while p is not None:
print(p.val, end='')
if p.next is not None:
print(", ", end='')
p = p.next
print('')
class Solution:
def reversePrint(self, head):
resList = []
while head:
resList.append(head.val)
head = head.next
return resList[::-1]
if __name__ == "__main__":
a = List()
a.add(3)
a.add(5)
a.add(9)
a.add(13)
a.printall()
b = Solution()
x = b.reversePrint(a.head)
print(x)
面试题06:从尾到头打印节点
猜你喜欢
转载自blog.csdn.net/worewolf/article/details/104934797
今日推荐
周排行