剑指Offer 3. 从尾到头打印链表 (链表)

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

题目地址

https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&tPage=1&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

思路

使用Python库函数,新建一个列表,使用insert每次插入到最前面,或者使用append最后在使用reverse。

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

# 单向链表链表 node1: 1->2->3
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node1.next = node2
node2.next = node3
node3.next = node4

class Solution:
    def printListFromTailToHead(self, listNode):
        # 方法1:使用insert函数
        # c = []
        # while listNode:
        #     c.insert(0,listNode.val)
        #     listNode = listNode.next
        # return c

        # 方法2:使用append,最后reverse
        c = []
        while listNode:
            c.append(listNode.val)
            listNode = listNode.next
        c.reverse()
        return c

if __name__ == '__main__':
    run = Solution()
    result = run.printListFromTailToHead(node1)
    print(result)

猜你喜欢

转载自www.cnblogs.com/huangqiancun/p/9775456.html