算法——剑指 Offer 06. 从尾到头打印链表
package com.xiao.algorithms;
/**
* 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
* 示例:
* 输入:head = [1,3,2]
* 输出:[2,3,1]
*/
public class Offer06_footer_to_header {
public static void main(String[] args) {
//创建一个链表
ListNode1 l1 = new ListNode1(1); //创建链表对象 l1 (对应有参 和 无参 构造方法)
l1.add(2); //插入结点,打印
l1.add(3);
l1.print();
System.out.println(" ");
Offer06_footer_to_header aa = new Offer06_footer_to_header();
int[] results = aa.reversePrint(l1);
for(int result: results){
System.out.print(result+" ");
}
}
public int[] reversePrint(ListNode1 head) {
//计数就完事
ListNode1 cur = head;
int count = 0;
while (cur != null) {
cur = cur.next;
count++;
}
int[] arr = new int[count];
cur = head;
count--;
while (cur != null && count >= 0) {
arr[count--] = cur.val;
cur = cur.next;
}
return arr;
}
}
//创建一个链表的类
class ListNode1{
int val; //数值 data
ListNode1 next; // 结点 node
ListNode1(int x){ //可以定义一个有参构造方法,也可以定义一个无参构造方法
val = x;
}
// 添加新的结点
public void add(int newval) {
ListNode1 newNode = new ListNode1(newval);
if(this.next == null)
this.next = newNode;
else
this.next.add(newval);
}
// 打印链表
public void print() {
System.out.print(this.val);
if(this.next != null)
{
System.out.print("-->");
this.next.print();
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律