数据结构与算法

从尾到头打印链表

2019-12-21  本文已影响0人  而立之年的技术控
微信图片_20191221160845.jpg
############# 【第一种遍历】###############
class Solution:
    def __init__(self):
        self.result = []
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        while listNode:
            self.result.insert(0,listNode.val)
            listNode = listNode.next
        return self.result
############# 【第二种,先反转,再遍历】###############
class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        if listNode is None:
            return []
        if listNode.next is None:
            return listNode
        pre = listNode
        cur = listNode.next
        last = listNode.next.next
        pre.next = None
        while last != None:
            cur.next = pre
            pre = cur
            cur = last
            last = last.next
        cur.next = pre
        
        result = []
        while cur != None:
            result.append(cur.val)
            cur = cur.next
        return result
上一篇 下一篇

猜你喜欢

热点阅读