当前位置:网站首页>剑指 Offer 06. 从尾到头打印链表
剑指 Offer 06. 从尾到头打印链表
2022-07-28 10:28:00 【jjj34】
题目描述

思路:利用栈的后进先出的特性来实现
1.创建栈
2.遍历链表,将链表节点对应的值入栈
3.声明一个数组,长度为栈的长度,出栈
知识点:栈,链表
栈的相关知识点:参考这篇博客
剑指 Offer 09. 用两个栈实现队列_jcxj2934的博客-CSDN博客
链表的相关知识点:

如图,链表这个数据结构中包含了三个值,
第一个是整数, 即节点对应的值
第二个是指针,即指向下一个节点(作用:将链表连接起来)

如图,正因为有了指向下一个节点的指针,链表才能连接起来
末尾节点没有指向的对象,指针的值为null
第三个是赋值,给链表中的节点赋值
代码如下
/**
* 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<Integer> st;
st=new Stack<>();
while(head != null) //利用尾节点的指针值为null来判断链表是否全部遍历
{
st.push(head.val);
head=head.next;
}
int n =st.size();
int result[] = new int [n];
int i=0;
while(!st.empty())
{
result[i]=st.pop();
i++;
}
return result;
}
}
边栏推荐
猜你喜欢

Attention attention mechanism flow chart

乱打日志的男孩运气怎么样我不知道,加班肯定很多

Markdown to word or PDF

7. MapReduce custom sorting implementation

爱可可AI前沿推介(7.28)

Configuring raspberry pie, process and problems encountered

Redis-day01-常识补充及redis介绍

SQL Server 2016 learning records - set query

Machine learning -- handwritten English alphabet 1 -- classification process

Batch Normlization
随机推荐
GKCoherentNoiseSource
Test question discovery ring of previous test questions
SemEval 2022 | 将知识引入NER系统,阿里达摩院获最佳论文奖
markdown转成word或者pdf
Aike AI frontier promotion (7.28)
nodemcu之开发环境配置
GKPerlinNoiseSource
GKLinearCongruentialRandomSource
GKCylindersNoiseSource
GKPerlinNoiseSource
Configuring raspberry pie, process and problems encountered
Pyqt5 rapid development and practice 4.12 calendar and time
GKNoise
GKObstacle
粒子群实现最优解的求解
GKBillowNoiseSource
GKARC4RandomSource
GKConstantNoiseSource
Pyqt5 rapid development and practice 4.11 drag and clipboard
OCR 知识 概括