温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

LeetCode如何从尾到头打印链表

发布时间:2021-12-15 14:41:29 来源:亿速云 阅读:126 作者:小新 栏目:大数据

这篇文章将为大家详细讲解有关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如何从尾到头打印链表”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI