当前位置:网站首页>剑指 Offer 06. 从尾到头打印链表
剑指 Offer 06. 从尾到头打印链表
2022-07-05 08:16:00 【程序员·小李】
题目:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入: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) {
Stack<ListNode> stack = new Stack<>();
int counter = 0;
while(head != null){
counter++;
stack.push(head);
head = head.next;
}
int[] array = new int[counter];
for (int i = 0; i < counter; i++){
array[i] = stack.pop().val;
}
return array;
}
}
边栏推荐
- Let's briefly talk about the chips commonly used in mobile phones - OVP chips
- Hardware and software solution of FPGA key chattering elimination
- C WinForm [change the position of the form after running] - Practical Exercise 4
- Makefile application
- 实例009:暂停一秒输出
- Working principle and type selection of common mode inductor
- Stm32--- systick timer
- Tailq of linked list
- 【论文阅读】2022年最新迁移学习综述笔注(Transferability in Deep Learning: A Survey)
- STM32 --- NVIC interrupt
猜你喜欢
STM32 single chip microcomputer - external interrupt
Explain task scheduling based on Cortex-M3 in detail (Part 2)
Installation and use of libjpeg and ligpng
NTC thermistor application - temperature measurement
Network communication process
[trio basic tutorial 17 from getting started to mastering] set up and connect the trio motion controller and input the activation code
Stm32--- systick timer
C WinForm [exit application] - practice 3
Stablq of linked list
Reasons for rapid wear of conductive slip rings
随机推荐
QEMU demo makefile analysis
Management and use of DokuWiki
Google sitemap files for rails Projects - Google sitemap files for rails projects
NTC thermistor application - temperature measurement
Measurement fitting based on Halcon learning [II] meaure_ pin. Hdev routine
STM32 tutorial triple ADC interleaved sampling
How to select conductive slip ring
My-basic application 1: introduction to my-basic parser
STM32 single chip microcomputer -- debug in keil5 cannot enter the main function
go依赖注入--google开源库wire
Communication standard -- communication protocol
C WinForm [view status bar -- statusstrip] - Practice 2
Void* C is a carrier for realizing polymorphism
Wifi-802.11 negotiation rate table
Explain task scheduling based on Cortex-M3 in detail (Part 2)
Consul installation
实例006:斐波那契数列
My-basic application 2: my-basic installation and operation
Hardware 1 -- relationship between gain and magnification
Problem solving: interpreter error: no file or directory