当前位置:网站首页>来n遍剑指--06. 从尾到头打印链表
来n遍剑指--06. 从尾到头打印链表
2022-07-31 08:57:00 【秦 羽】
专栏前言:
本专栏主要是算法训练,目的很简单。在掌握基本的java知识后,学习最重要的算法知识,在学习之前首先要对自身有一定的理解,如果不知道怎么做欢迎来私聊。
算法的过程很枯燥,但是也很特别,不断地刷题,不断地分享才会越来越好,给别人讲明白才是真正学会了。在分享中学会知识。
坚持就是胜利~~~
题目描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
解题1:
我的比较简单,思路是让指针到最后并且得到链表长度;创建等长度的数组,数组最后一位保存链表第一位的值,以此类推。得到最终的值
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public int[] reversePrint(ListNode head) {
int num = 0;
ListNode res = head;
while(res != null){
num++;
res = res.next;
}
int result[] = new int[num];
while(head != null){
result[--num] = head.val;
head = head.next;
}
return result;
}
}
解题2:
官方解题思路
栈的特点是后进先出,即最后压入栈的元素最先弹出。考虑到栈的这一特点,使用栈将链表元素顺序倒置。从链表的头节点开始,依次将每个节点压入栈内,然后依次弹出栈内的元素并存储到数组中。
- 创建一个栈,用于存储链表的节点
- 创建一个指针,初始时指向链表的头节点
- 当指针指向的元素非空时,重复下列操作:
- 将指针指向的节点压入栈内
- 将指针移到当前节点的下一个节点
- 获得栈的大小 size,创建一个数组 print,其大小为 size
- 创建下标并初始化 index = 0
- 重复 size 次下列操作:
- 从栈内弹出一个节点,将该节点的值存到 print[index]
- 将 index 的值加 1
/** * 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>();
ListNode temp = head;
while (temp != null) {
stack.push(temp);
temp = temp.next;
}
int size = stack.size();
int[] print = new int[size];
for (int i = 0; i < size; i++) {
print[i] = stack.pop().val;
}
return print;
}
}
课后习题:
没有啦

边栏推荐
猜你喜欢

How to Install MySQL on Linux

高并发高可用高性能的解决方案

SQL join table (inner join, left join, right join, cross join, full outer join)

35-Jenkins-Shared library application

2019 NeurIPS | Graph Convolutional Policy Network for Goal-Directed Molecular Graph Generation

51单片机-----外部中断

【黄啊码】MySQL入门—3、我用select ,老板直接赶我坐火车回家去,买的还是站票
![[Cloud native and 5G] Microservices support 5G core network](/img/c9/4ccacd1e70285c2ceb50c324e5018c.png)
[Cloud native and 5G] Microservices support 5G core network

SSM integration case study (detailed)

MySQL (2)
随机推荐
【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(下) -- 搜索历史
关于@Autowired
【云原生&微服务五】Ribbon负载均衡策略之随机ThreadLocalRandom
Hematemesis summarizes thirteen experiences to help you create more suitable MySQL indexes
状态机动态规划之股票问题总结
【RISC-V】risc-v架构学习笔记(架构初学)
剑指offer-解决面试题的思路
Golang-based swagger super intimate and super detailed usage guide [there are many pits]
搭建frp进行内网穿透
JSP pagecontext对象的简介说明
A, MySQL principle of master-slave replication
Kotlin 优点
高并发高可用高性能的解决方案
[Mini Program Project Development--Jingdong Mall] Custom Search Component of uni-app (Part 1)--Component UI
刷题《剑指Offer》day05
SSM框架讲解(史上最详细的文章)
SQL 嵌套 N 层太长太难写怎么办?
如何升级nodejs版本
Splunk Workflow action 给我们带来的好处
蚂蚁核心科技产品亮相数字中国建设峰会 持续助力企业数字化转型