【数组与链表】剑指 Offer 06. 从尾到头打印链表

题目描述:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例
输入:head = [1,3,2]
输出:[2,3,1]

题解1:想麻烦了,先把链表反转了,然后再取值

# 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]:
        cur = head
        pre = None
        while cur:
            tmp = cur.next
            cur.next = pre
            #tmp.next = cur
            pre = cur 
            cur = tmp
        result = []
        cur = pre
        while cur:
            result.append(cur.val)
            cur = cur.next
        return result

题解2:根本不用反转链表,因为输出只要是数组的形式,所以利用栈先进后出的原理,创建一个辅助栈,就可以反转结果了。

# 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]:
        stack = []
        while head:
            stack.append(head.val)
            head = head.next
       #return stack[::-1] ##或者直接在这return这个
        result = []
        while stack:
            result.append(stack.pop()) 
        return result

猜你喜欢

转载自blog.csdn.net/Rolandxxx/article/details/128889059