简体   繁体   中英

A little help needed on my project

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;
}

Add this to the Node class:

public void printReverse() {

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

  System.out.println(data);
}

and this to the 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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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