我的项目需要一点帮助
我正在开发一个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;
}
I'm developing a JAVA project as my assigment. In a part of LinkedList class I stucked on recursion. Can anyone help me about writing this function? The question is How to Write a recursive instance method for the LinkedList class that prints the linked list instance in reverse order and lenght of the LinkedList lenght (I guess with different two functions)?
My LinkedList class is like:
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;
}
}
For ex this is my insert recursive method for 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
用于计算链表的长度
For computing the length of the linked list
将其添加到 Node 类:
并将其添加到
LinkedList
类:您应该尝试更改此代码以正常打印列表:)(这是一个非常简单的更改)。
Add this to the Node class:
and this to the
LinkedList
class:You should try to change this code to print the list normally :) (It's a very simple change).
通常的方法是使用“当前”列表元素(从第一个列表节点开始)调用遍历方法。该方法检查它是否具有列表的最后一个元素。如果没有,则使用下一个元素递归调用该方法。然后打印出当前元素的值。
The usual way of doing this is to call your traverse method with the "current" list element (which starts as the first list node). The method checks to see if it has the last element of the list. If it doesn't, recursively call the method with the next element. Then print out the value of the current element.