Serkan Hekimoglu
Serkan Hekimoglu

Reputation: 4284

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

Upvotes: 0

Views: 132

Answers (3)

Pravin
Pravin

Reputation: 1059

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

Upvotes: 1

Mihai Toader
Mihai Toader

Reputation: 12243

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).

Upvotes: 1

GreenMatt
GreenMatt

Reputation: 18580

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.

Upvotes: 0

Related Questions