1. 程式人生 > >劍指offer刷題之從尾到頭列印連結串列

劍指offer刷題之從尾到頭列印連結串列

輸入一個連結串列,按連結串列值從尾到頭的順序返回一個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):
        # write code here
        result =[]
        if listNode is None:
            return result
        while listNode.next is not None:
            result.append(listNode.val)
            listNode = listNode.next
        result.append(listNode.val)
        return result[::-1]

 遞迴方法:

# -*- 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
        if listNode is None:
            return []
        return self.printListFromTailToHead(listNode.next) + [listNode.val]

出棧:pop函式

# -*- 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
        lst,lst_bak = [],[]
        if not listNode:
            return lst
        while listNode:
            lst.append(listNode.val)
            listNode = listNode.next
        while lst:
            lst_bak.append(lst.pop())
        return lst_bak