面试题06.从头到尾打印链表

面试题06.从头到尾打印链表

题目描述

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

示例 1:

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

限制:

0 <= 链表长度 <= 10000

题解

从尾到头反过来返回每个节点的值,很容易想到借助栈来完成,先按顺序存入栈,之后出栈入数组即得结果,代码如下

/**
 * 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[] res = new int[stack.size()];
        for(int x=0;x<res.length;x++){
            res[x] = stack.pop();           
        }
        return res;
    }
}
提交结果

在这里插入图片描述

发布了21 篇原创文章 · 获赞 19 · 访问量 586

猜你喜欢

转载自blog.csdn.net/weixin_44458246/article/details/104286758