# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defreversePrint(self, head: ListNode) -> List[int]: res = [] p = head while p: res.append(p.val) p = p.next ## 列表反转的两种方法 res = res[::-1] # res.reverse() return res
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defreversePrint(self, head: ListNode) -> List[int]: res = [] if head == None: return res prev = None cur = head temp = cur.next while cur: temp = cur.next cur.next = prev prev = cur cur = temp p = prev while p: res.append(p.val) p = p.next return res