题目描述
输入一个链表,从尾到头打印链表每个节点的值。
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, listNode): result = [] while listNode is not None: result.append(listNode.val) listNode = listNode.next return result[::-1]
其中:1:self.next=None是为什么?是定义了最后一个节点吗?
2:注意写法is None,is not None
3:[::-1]利用切片实现倒序
链接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035
来源:牛客网
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
# -*- coding:utf-8-*-
# classListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
classSolution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def
printListFromTailToHead(
self
, listNode):
# write code here
result
=
[]
iflistNode
is
None
:
returnresult
whilelistNode.
next
is
not
None
:
result.extend([listNode.val])
listNode
=
listNode.
next
result.extend([listNode.val])
returnresult[::
-
1
]
|
其中,第34行result.extend([listNode.val])再写一遍是为什么?
不写的话会出现错误:
测试用例:
{67,0,24,58}对应输出应该为:
[58,24,0,67]
你的输出为:
[24,0,67]