面試6題:
題目:從尾到頭打印鏈表
輸入一個鏈表,從尾到頭打印鏈表每個節點的值。
解題代碼:
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回從尾部到頭部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, listNode): # write code here if not listNode: return [] res=[] while listNode.next is not None: res.append(listNode.val) listNode=listNode.next res.append(listNode.val) return res[::-1]