• 从尾到头打印链表


    题目描述

    输入一个链表,从尾到头打印链表每个节点的值。

    输入描述:

    输入为链表的表头

    输出描述:

    输出为需要打印的“新链表”的表头
     

    解法一:递归实现(效率低)

    import java.util.ArrayList; class ListNode{ int val; ListNode next = null; ListNode(int val) { this.val = val; } } public class Solution { static ArrayList<Integer> arrayList = new ArrayList<Integer>(); public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) { if (listNode != null) { printListFromTailToHead(listNode.next); arrayList.add(listNode.val); } return arrayList; } public static void main(String[] args) { ListNode a = new ListNode(1); ListNode b = new ListNode(2); ListNode c = new ListNode(3); a.next = b; b.next = c; System.out.println(printListFromTailToHead(a)); } }

    解法

    二:借助栈实现复杂度为O(n)

    class ListNode{ int val; ListNode next = null; ListNode(int val) { this.val = val; } } public class Solution { public static ArrayList<Integer> printListFromTailToHead(ListNode1 listNode) { Stack<Integer> stack = new Stack<Integer>(); ArrayList<Integer> arry = new ArrayList<Integer>(); while (listNode != null) { stack.push(listNode.val); listNode = listNode.next; } while (!stack.empty()) { arry.add(stack.pop()); } return arry; } public static void main(String[] args) { ListNode1 a = new ListNode1(1); ListNode1 b = new ListNode1(2); ListNode1 c = new ListNode1(3); a.next = b; b.next = c; System.out.println(printListFromTailToHead(a)); } }

  • 相关阅读:
    (PHP)redis Zset(有序集合 sorted set)操作
    (PHP)redis Set(集合)操作
    (PHP)redis Hash(哈希)操作
    (PHP)redis String(字符串)操作
    (PHP)redis List(列表)操作
    PHP连接 redis
    PHP json 对象 数组互相转换
    循环节长度 蓝桥杯
    三羊献瑞 蓝桥杯
    立方变自身
  • 原文地址:https://www.cnblogs.com/0xcafedaddy/p/5258333.html
Copyright © 2020-2023  润新知