微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

LeetCode如何从尾到头打印链表

这篇文章将为大家详细讲解有关LeetCode如何从尾到头打印链表,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。


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,题解程序图片

LeetCode如何从尾到头打印链表

关于“LeetCode如何从尾到头打印链表”这篇文章分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐