题目
python题解
class ListNode(object):
def __init__(self):
self.val = None
self.next = None
#尾插法
def creatlist_tail(lst):
L = ListNode() #头节点
first_node = L
for item in lst:
p = ListNode()
p.val = item
L.next = p
L = p
return first_node
#头插法
def creatlist_head(lst):
L = ListNode() #头节点
for item in lst:
p = ListNode()
p.val = item
p.next = L
L = p
return L
#打印linklist
def print_ll(ll):
while True:
if ll.val:
print(ll.val)
if ll.next==None: #尾插法停止点
break
elif not ll.next: #头插法停止点
break
ll = ll.next
#题解
class Solution:
def printListFromTailToHead(self, listNode):
# write code here
res = []
while(listNode):
res.append(listNode.val)
listNode=listNode.next
return res[3:0:-1]
if __name__ == "__main__":
lst = [1, 2, 3]
linklist = creatlist_tail(lst)
solution = Solution()
res = solution.printListFromTailToHead(linklist)
print(res)
结果
[3, 2, 1]