剑指offer 06 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
其实就是反转链表,设置一个pre是虚拟头结点,cur指向头结点head,然后首先保存cur的下一个值temp,然后依次把指针的指向更换以及pre和cur更新,如果cur为空的时候结束,此时这个链表的头结点就是pre,然后依次把值放进数组。
# 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]:
dummy = ListNode(val = None, next = head)
pre = None
cur = head
while cur != None:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
ans = []
while pre:
ans.append(pre.val)
pre = pre.next
return ans