leetcode-从尾到头打印链表

 题目来自LeetCode,链接:面试题06. 从尾到头打印链表。具体描述:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

 示例:

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

 首先可以利用栈保存遍历链表各节点得到的值,然后因为栈的特性(先进后出)出栈的时候得到的就是反向的各节点的值了,时间复杂度为 O ( n ) O(n) O(n),空间复杂度为 O ( n ) O(n) O(n)

 JAVA版代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        while (head != null) {
            stack.push(head.val);
            head = head.next;
        }
        int size = stack.size();
        int[] result = new int[size];
        for (int i = 0; i < size; ++i) {
            result[i] = stack.pop();
        }
        return result;
    }
}

 提交结果如下:


 然后可以用反转链表的方法,时间复杂度为 O ( n ) O(n) O(n),空间复杂度为 O ( 1 ) O(1) O(1)

 JAVA版代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        if (head == null) {
            return new int[0];
        }
        int count = 0;
        ListNode prev = head;
        ListNode next = head.next;
        head.next = null;
        while (next != null) {
            head = next;
            next = head.next;
            head.next = prev;
            prev = head;
            ++count;
        }
        int[] result = new int[count + 1];
        int i = 0;
        while (head != null) {
            result[i++] = head.val;
            head = head.next;
        }
        return result;
    }
}

 提交结果如下:


 Python版代码如下:

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

 提交结果如下:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值