Python3-[5]面试题06.从尾到头打印链表( 栈的应用/遍历)

Python3-[5]面试题06.从尾到头打印链表

      • 题目
        • 解法1:队列
        • code:队列-插入res头部
        • 解法2:辅助栈
        • code2:辅助栈
        • 解法3:递归

题目

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
P.S. 题目来源于leetcode,这是我的题解

解法1:队列

遍历一次链表,值插入到res头部。

code:队列-插入res头部

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
from collections import deque
class Solution:
    def reversePrint(self, head):
        #一次遍历链表
        #res =  []
        res = deque()
        while head:
            #res.insert(0, head.val)
            res.appendleft(head.val)
            head = head.next
        return list(res)

解法2:辅助栈

添加到res中,倒序输出即可

code2:辅助栈

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
	def reversePrint(self, head):
		res = []
		while head:
			res.append(head.val)
			head = head.next
		return res[::-1]

解法3:递归

递归到末节点,回溯的时候依次添加节点的val即可。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
	def reversePrint(self, head):
		self.res = []
		def DFS(head):
			if not head: return 
			DFS(head.next)
			self.res.append(head.val)
			return 
		DFS(head)
		return self.res

你可能感兴趣的:(剑指系列,数据结构与算法)