当前位置:网站首页>Come n times - 06. Print the linked list from end to end
Come n times - 06. Print the linked list from end to end
2022-07-31 09:02:00 【Qin Yu】
专栏前言:
本专栏主要是算法训练,目的很简单.在掌握基本的java知识后,Learn the most important algorithm knowledge,Before learning, you must first have a certain understanding of yourself,If you don't know how to do it, welcome to chat privately.
The algorithmic process is boring,But also very special,不断地刷题,The more you share, the better it gets,The only way to truly learn is to explain it to others.Learn knowledge by sharing.
坚持就是胜利~~~
题目描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回).
示例:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
解题1:
我的比较简单,The idea is to let the pointer go to the end and get the length of the linked list;Create arrays of equal length,The last bit of the array holds the value of the first bit of the linked list,以此类推.得到最终的值
/** * 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;
}
}
课后习题:
没有啦

边栏推荐
猜你喜欢
随机推荐
The torch distributed training
HTC官方RUU固件提取刷机包rom.zip以及RUU解密教程
多版本node的安装与切换详细操作
qt在不同的线程中传递自定义结构体参数
奉劝那些刚参加工作的学弟学妹们:要想进大厂,这些核心技能是你必须要掌握的!完整学习路线!
【MySQL功法】第4话 · 和kiko一起探索MySQL中的运算符
Kotlin 优点
MySQL 日期时间类型精确到毫秒
二叉树的搜索与回溯问题(leetcode)
Cloud server deployment web project
JSP session的生命周期简介说明
JSP pagecontext对象的简介说明
(C语言基础)原样输入输出
matlab常用符号用法总结
【MySQL功法】第3话 · MySQL中常见的数据类型
基于学生成绩管理系统(附源代码及数据库)
Flutter Paystack implements all options
SSM整合案例分析(详解)
刷题《剑指Offer》day05
【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(下) -- 搜索历史








