【链表】从尾到头打印链表

2019-08-14  本文已影响0人  一个想当大佬的菜鸡
  • 打印后翻转列表
  • 翻转后打印
class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        res = []
        p = listNode
        while p:
            res.append(p.val)
            p = p.next
        i, j = 0, len(res)-1
        while i < j:
            res[i], res[j] = res[j], res[I]
            i += 1
            j -= 1
        return res
class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        if not listNode:
            return []
        res = []
        pre = None
        now = listNode
        nxt = listNode.next
        while now and nxt:
            now.next = pre
            pre = now
            now = nxt
            nxt = nxt.next
        now.next = pre
        p = now
        while p:
            res.append(p.val)
            p = p.next
        return res
上一篇 下一篇

猜你喜欢

热点阅读