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