首页 > 编程语言 > 详细

数组练习(二):从尾到头打印链表

时间:2021-08-17 23:07:59      阅读:17      评论:0      收藏:0      [点我收藏+]

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

示例:

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

  

解题思路:

  • 首先这个链表的长度第一时间无法确认,所以无法直接使用下标的方式创建数组
  • 其次需要从尾到头反过来输出数组,想到使用栈的【先入后出】的特点,所以使用栈作为中间容器,对元素进行临时存储,再通过出栈的方式,将栈内元素倒序。
package Algriothm;

import java.util.Arrays;
import java.util.Stack;

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

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode head1 = new ListNode(3);
        ListNode head2 = new ListNode(2);
        head.next = head1;
        head1.next = head2;
        int[] ints = reversePrint(head);
        System.out.println(Arrays.toString(ints));
    }

    public static int[] reversePrint(ListNode head) {
        ListNode cur = head;
        Stack<Integer> stack = new Stack<Integer>();
        while (cur != null) {
            stack.push(cur.val);
            cur = cur.next;
        }
        int[] res = new int[stack.size()];
        int size = stack.size();
        for (int i = 0; i < size; i++) {
            res[i] = stack.pop();
        }
        return res;
    }
}


class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

  

数组练习(二):从尾到头打印链表

原文:https://www.cnblogs.com/yssd/p/15153927.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!