简体   繁体   English

我的项目需要一点帮助

[英]A little help needed on my project

I'm developing a JAVA project as my assigment.我正在开发一个 JAVA 项目作为我的任务。 In a part of LinkedList class I stucked on recursion.在 LinkedList class 的一部分中,我坚持使用递归。 Can anyone help me about writing this function?谁能帮我写这个 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)?问题是如何为 LinkedList class 编写递归实例方法,该方法以相反的顺序和 LinkedList 长度的长度打印链表实例(我猜有不同的两个函数)? My LinkedList class is like:我的 LinkedList class 就像:

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例如,这是我的 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;
}

Add this to the Node class:将此添加到节点 class:

public void printReverse() {

  if ( next != null ) {
    next.printReverse();
  }

  System.out.println(data);
}

and this to the LinkedList class:这个链接到LinkedList class:

print void printReverse() {
  System.out.println("(");

  if ( first == null ) {
    first.printReverse();
  }

  System.out.println(")");
}

You should try to change this code to print the list normally:) (It's a very simple change).您应该尝试更改此代码以正常打印列表:)(这是一个非常简单的更改)。

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

For computing the length of the linked list用于计算链表的长度

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

The usual way of doing this is to call your traverse method with the "current" list element (which starts as the first list node).执行此操作的常用方法是使用“当前”列表元素(从第一个列表节点开始)调用您的 traverse 方法。 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.然后打印出当前元素的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM