美文网首页数据结构与算法
从尾到头打印链表

从尾到头打印链表

作者: 而立之年的技术控 | 来源:发表于2019-12-21 16:16 被阅读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
    

    相关文章

      网友评论

        本文标题:从尾到头打印链表

        本文链接:https://www.haomeiwen.com/subject/qwygnctx.html