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

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

    示例 1:

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

    限制:

    0 <= 链表长度 <= 10000

    题解1:(取巧方法,不通用)

      思路如下:

      首先算出链表的长度

      创建保存结果的数组

      然后再遍历一遍,从尾部开始

    复杂度分析:

      时间复杂度:O(n)

      空间复杂度:O(n)

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution {
    10     public int[] reversePrint(ListNode head) {
    11         ListNode node = head;
    12         int count=0;
    13         while(node!=null){
    14             count++;
    15             node=node.next;
    16         }
    17         int ans[]=new int [count];
    18         node=head;
    19         for(int i=count-1;i>=0;i--){
    20             ans[i]=node.val;
    21             node=node.next;
    22             
    23         }
    24         return ans;
    25 
    26     }
    27 }

     题解2:递归法

      思路如下:

      利用递归: 先走至链表末端,回溯时依次将节点值加入列表 ,这样就可以实现链表值的倒序输出。

      递推阶段: 每次传入 head.next ,以 head == null(即走过链表尾部节点)为递归终止条件,此时直接返回。

      回溯阶段: 层层回溯时,将当前节点值加入列表,即tmp.add(head.val)。

      最终,将列表 tmp 转化为数组 res ,并返回即可。

    复杂度分析:

      时间复杂度 O(N)O(N): 遍历链表,递归 N 次。

      空间复杂度 O(N)O(N): 系统递归需要使用 O(N) 的栈空间。

     1 class Solution {
     2     ArrayList<Integer> tmp = new ArrayList<Integer>();
     3     public int[] reversePrint(ListNode head) {
     4         recur(head);
     5         int[] res = new int[tmp.size()];
     6         for(int i = 0; i < res.length; i++)
     7             res[i] = tmp.get(i);
     8         return res;
     9     }
    10     void recur(ListNode head) {
    11         if(head == null) return;
    12         recur(head.next);
    13         tmp.add(head.val);
    14     }
    15 }

    题解3:辅助栈法

      思路如下:

      链表特点: 只能从前至后访问每个节点。
      题目要求: 倒序输出节点值。
      这种 先入后出 的需求可以借助 栈 来实现。

      步骤:

      入栈: 遍历链表,将各节点值 push 入栈。
      出栈: 将各节点值 pop 出栈,存储于数组并返回。

     1 class Solution {
     2     public int[] reversePrint(ListNode head) {
     3         LinkedList<Integer> stack = new LinkedList<Integer>();
     4         while(head != null) {
     5             stack.addLast(head.val);
     6             head = head.next;
     7         }
     8         int[] res = new int[stack.size()];
     9         for(int i = 0; i < res.length; i++)
    10             res[i] = stack.removeLast();
    11     return res;
    12     }
    13 }

    来源: https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/

     

  • 相关阅读:
    jQuery
    BOM与DOM操作
    剑指offer 面试题10.1:青蛙跳台阶
    剑指offer 面试题10:斐波那契数列
    剑指offer 面试题9.1:用两个队列实现栈
    剑指offer 面试题9.1:用两个队列实现栈
    剑指offer 面试题9:用两个栈实现队列
    剑指offer 面试题8:二叉树的下一个节点
    剑指offer 面试题7:重建二叉树
    剑指offer 树的基本操作:四种遍历方式
  • 原文地址:https://www.cnblogs.com/treasury/p/12595254.html
Copyright © 2011-2022 走看看