从尾到头打印链表

微信图片_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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容