zoukankan      html  css  js  c++  java
  • 从头到尾打印链表 (链表/栈)

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

    示例 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) {
            ListNode node = head;
            int length = 0;
            while(node!=null) {
                length++;
                node=node.next;
            }
    
            node = head;
            int[] array = new int[length];
            for (int i = length-1; i>=0; i--) {
                array[i] = node.val;
                node = node.next;
            }
            
            return array;
        }
    }
    

    方法二:利用栈先进后出的特性

    /**
     * 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<ListNode> stack = new Stack<>();
            ListNode node = head;
            while (node != null) {
                stack.push(node);
                node = node.next;
            }
    
            int length = stack.size();
            int[] array = new int[length];
            for (int i = 0; i < length; i++) {
                array[i] = stack.pop().val;
            }
            return array;
        }
    }
    
  • 相关阅读:
    绿豆加速器
    电脑派位系统(新生入学摇号) v2016
    硬盘安装win10
    msbuild
    async
    win sshd
    Ftp软件
    nginx basic auth 登陆验证模块
    深入理解docker的link机制
    Docker Compose to CoreOS
  • 原文地址:https://www.cnblogs.com/halo623/p/14556640.html
Copyright © 2011-2022 走看看