题目: 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)
思路:
链表的遍历只能从到尾,可以借用栈的入栈和出栈将访问得到的值顺序翻转
import numpy as np
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Stack:
def __init__(self):
self.s = np.array([], dtype=int)
self.length = 0
def append(self, e):
self.s = np.append(self.s, e)
self.length += 1
def delete(self):
e = self.s[self.length - 1]
self.s = np.delete(self.s, self.length - 1)
self.length -= 1
return e
def is_empty(self):
return self.length == 0
class Solution:
def reversePrint(self, head: ListNode):
result = np.array([])
stack = Stack()
curr = head
while curr:
stack.append(curr.val)
curr = curr.next
while not stack.is_empty():
result = np.append(result, stack.delete())
return result