【面试题】从尾到头打印链表(Java、Python实现)

题目描述

在这里插入图片描述

解法一:递归法

先遍历至链表末端,回溯时依次将节点值加入列表 ,这样就可以实现链表值的倒序输出。
时间复杂度 O(n): 遍历整个链表,需要递归 n 次。
空间复杂度 O(n): 系统递归调用需要 O(n) 的栈空间。

Python

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

class Solution(object):
    def reversePrint(self, head):
        """
        :type head: ListNode
        :rtype: List[int]
        """
        if not head: # 递归终止条件
            return []
        return self.reversePrint(head.next) + [head.val]

Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    ArrayList <Integer> tmp = new ArrayList <Integer>();
    public int[] reversePrint(ListNode head) {
        recur(head);
        // 将列表 tmp 转化为数组 res 返回(题目要求用数组返回)
        int[] res = new int[tmp.size()];
        for (int i=0; i<res.length; i++){
            res[i] = tmp.get(i);
        }
        return res;
    }
    // 定义递归函数
    public void recur(ListNode head){
        if (head == null) return; // 递归终止条件
        recur(head.next);
        tmp.add(head.val);
    }
}

解法二:辅助栈法

题目要求倒序输出节点值,这种 后进先出 的需求可以借助 来实现。
时间复杂度 O(n): 入栈和出栈共使用 O(n) 的时间。
空间复杂度 O(n): 辅助栈 stack 和数组 res 共使用 O(n) 的额外空间。。

Python

class Solution(object):
    def reversePrint(self, head):
        """
        :type head: ListNode
        :rtype: List[int]
        """
        stack = []
        while head: # 遍历至链表最后一个节点
            stack.append(head.val)
            head = head.next
        '''
        b = a[i:j:s]这种格式,s表示步进,缺省为1.
        当s<0时,i缺省时,默认为-1. j缺省时,默认为-len(a)-1.
        所以a[::-1]相当于 a[-1:-len(a)-1:-1],即倒序
        '''
        return stack[::-1] # 倒序输出

Java

注意:Vector 和 Stack者两个类,Java官方已经不推荐使用了。可以使用 java.util.Deque 双端队列来实现队列与栈的各种需求,也可以使用 LinkedList 实现。

下表列出了Deque与Stack对应的接口:
在这里插入图片描述

class Solution {
    public int[] reversePrint(ListNode head) {
        Deque<Integer> stack = new ArrayDeque<Integer> (); //或者 Deque<Integer> stack = new LinkedList<Integer> ();
        // 遍历链表节点,并压栈
        while (head != null){ 
            stack.push(head.val);
            head = head.next;
        }
        // 将stack 转化为数组 res 返回(题目要求用数组返回)
        int[] res = new int[stack.size()];
        for (int i=0; i<res.length; i++){ 
            res[i] = stack.pop(); // 弹出栈顶元素
        }
        return res;
    }
}


// 采用 LinkedList 实现栈
class Solution {
    public int[] reversePrint(ListNode head) {
        LinkedList<Integer> stack = new LinkedList<Integer> ();
        // 遍历链表节点,并压栈
        while (head != null){ 
            stack.addLast(head.val);
            head = head.next;
        }
        // 将LinkedList 转化为数组 res 返回(题目要求用数组返回)
        int[] res = new int[stack.size()];
        for (int i=0; i<res.length; i++){ 
            // 注意:在 removeLast()的过程中,stack.size()在变化,因此 for循环的每轮判断若写成 i<stack.size()会出问题
            res[i] = stack.removeLast(); // 弹出栈顶元素
        }
        return res;
    }
}

参考

https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/mian-shi-ti-06-cong-wei-dao-tou-da-yin-lian-biao-d/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值