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

标签:链表

题目

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

输入: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) {
Deque<Integer> res = new LinkedList<>();
int count = 0; while (head != null) {
res.offerFirst(head.val);
head = head.next;
count++;
} int[] values = new int[count];
count = 0;
while (!res.isEmpty()) {
values[count++] = res.poll();
} return values;
}
}

时间复杂度O(n),空间复杂度O(n)

解法二

/**
* 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 node1 = head;
int count = 0;
while (node1 != null) {
count++;
node1 = node1.next;
} int[] nums = new int[count];
ListNode node2 = head;
while (node2 != null) {
nums[--count] = node2.val;
node2 = node2.next;
} return nums;
}
}

时间复杂度O(n), 空间复杂度O(n)

最新文章

  1. 无法启动WP Emulator
  2. Powershell获取并导出指定日期EventLog
  3. net-snmp的MIBs扩展(linux下)
  4. ios截取号码
  5. zoj3551 Bloodsucker ——概率DP
  6. Kali Linux Web 渗透测试视频教—第二十课-利用kali linux光盘或者usb启动盘破解windows密码
  7. android:descendantFocusability=”blocksDescendants”的用法
  8. javascript中数组常用方法总结
  9. [ An Ac a Day ^_^ ] [kuangbin带你飞]专题四 最短路练习 POJ 3259 Wormholes
  10. 其他应用和技巧-用JS实现的抽奖程序
  11. nginx配置文件详细解读
  12. 查看CentOS版本
  13. Mysql临时文件目录控制
  14. Shiro学习总结(1)——Apache Shiro简介
  15. ubuntu通过apt-get安装JDK8
  16. Python中结巴分词使用手记
  17. [UE4]虚幻4的网络适合开发什么游戏
  18. Java基础——注释规范
  19. 十一、springboot之web开发之Filter
  20. OC开发_Storyboard——多线程、UIScrollView

热门文章

  1. Python爬虫之-动态网页数据抓取
  2. React-列表 & Key
  3. SQL注入平台第一关,注入?id=1&#39;不报错的问题
  4. windows 7系统封装总结
  5. net5学习笔记---依赖注入
  6. 【Mybatis源码解析】- 整体架构及原理
  7. iNeuOS工业互联平台,WEB组态(iNeuView)增加动态图元,例如液位
  8. mac 安装jmeter
  9. Date类常用方法总结(构造|格式化输出|String转换|Long转换|计算间隔|比较)
  10. vue2.0与3.0响应式原理机制