剑指offer 从尾到头打印链表 Posted on 2019-02-22 | 从尾到头打印链表题目类似于Leetcode 206.反转链表输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。 方法方法1:按顺序访问链表,反转结果123456789101112131415161718192021# -*- coding:utf-8 -*-# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, listNode): # write code here if not listNode: return [] elif not listNode.next: return [listNode.val] ans=[] while listNode: ans.append(listNode.val) listNode=listNode.next ans.reverse() return ans 方法2:反转链表123456789101112131415161718192021222324# -*- coding:utf-8 -*-# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, listNode): # write code here if not listNode: return [] elif not listNode.next: return [listNode.val] ans=[] pre=None while listNode: ans.insert(0,listNode.val) tmp=listNode.next listNode.next=pre pre=listNode listNode=tmp return ans Leetcode Solution