LeetCode106|从尾到头打印链表

时间:2022-07-28
本文章向大家介绍LeetCode106|从尾到头打印链表,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

0x01,问题简述

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

0x02 ,示例

示例 1:

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

限制:

0 <= 链表长度 <= 10000

0x03,题解思路

栈结构进行解决,已有的数据结构Stack

0x04,题解程序


import java.util.Stack;

public class ReversePrintTest {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(3);
        ListNode l3 = new ListNode(2);
        l1.next = l2;
        l2.next = l3;
        int[] reversePrint = reversePrint(l1);
        for (int num : reversePrint
        ) {
            System.out.print(num + "t");
        }

    }

    public static int[] reversePrint(ListNode head) {
        if (head == null) {
            return new int[0];
        }
        if (head.next == null) {
            return new int[]{head.val};
        }
        Stack<Integer> stack = new Stack<>();
        ListNode tempNode = head;
        while (tempNode != null) {
            stack.push(tempNode.val);
            tempNode = tempNode.next;
        }
        int[] result = new int[stack.size()];

        int index = 0;
        while (!stack.isEmpty()) {
            result[index] = stack.pop();
            index++;
        }
        return result;
    }
}

0x05,题解程序图片版

0x06,总结一下

这是自己写的第106篇leetcode题解,纯java语言编写,基本上就会提供一种思路进行解决,写到这里,自己主要是为了将以往做过的内容进行了回顾,没有新增的内容,利用自己的时间将做过的内容都以文章的形式进行输出