gpt4 book ai didi

java - 我的项目需要一点帮助

转载 作者:行者123 更新时间:2023-12-02 08:18:48 24 4
gpt4 key购买 nike

我正在开发一个 JAVA 项目作为我的任务。在 LinkedList 类的一部分中,我坚持递归。谁能帮我写这个函数?问题是如何为 LinkedList 类编写一个递归实例方法,以相反的顺序和 LinkedList 长度的长度打印链表实例(我猜有不同的两个函数)?我的 LinkedList 类如下:

public class Node
{
public int data;
public Node next;
public Node (int data)
{
this.data = data;
}
}

public class LinkedList
{
private Node first;
public LinkedList
{
first = null;
}
}

例如,这是我的 LinkedList 插入递归方法

private void insertRec(Node n, int data)
{
if(n == null)
{
Node newNode = new Node(data);
return newNode;
}

if(data > n.data)
n.next = insertRec(n.next,data);
return n;
}

最佳答案

public static void reversePrint (LinkedList l)
{
if (l != null) {
reversePrint(l.next);
System.out.println(l.value);
}
}

用于计算链表的长度

 public static int length (LinkedList l)
{
if (l == null)
return 0;
else
return 1 + length(l.next);
}

关于java - 我的项目需要一点帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5859645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com