Topic
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
Solution one: create a new list, the value of the linked list, traversing a list and added to the list, using the reverse () function of the reverse elements in this list, returns a list of the reverse
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
result = []
while head!=None:
result.append(head.val) # 将链表的值依次加入列表result
head = head.next
result.reverse() # 反向列表中元素
return result
Solution II: traverse the list, the list of values using insert () function into Result list, returns a list of
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
result = []
while head!=None:
result.insert(0,head.val)
head = head.next
return result