简体   繁体   中英

java recursive linked list

     private Node<T> recremoveFirst (Node<T> list, T element)
     {

 if (list == null)
     return null;
 else if(list.next == element)
     return list.next;
 else{
     list.next = recremoveFirst(list.next, element);
     return list;
 }

 }//calling recursive method
     public void removeFirst(T element) {

    recremoveFirst(head, element);

 }
 int choice;
Element elem;//constructor public Element (String name, int no)

LinkedList<Element> list = new LinkedList<Element>();

String name;
int number;
case 1 :  // addFirst
      System.out.print("Type name and number: ");
      name = Cin.readString();
      number = Cin.readInt();
      list.addFirst(new Element(name,number));
      break;
    case 2 :  // addLast
      System.out.println("Enter name and number to add last element: ");
      name = Cin.readString();
      number = Cin.readInt();
      list.addLast(new Element(name, number));
      break;

 case 3 :  // removeFirst

        list.removeFirst(elem);

When I'm trying to test this recursive method it shows me an error near list.removeFirst(elem); and gives only suggestion initialize it even though it is initialized(if press initialize sets it to null). So I wonder what's is that I'm doing wrong. Error mssage: Multiple markers at this line - The local variable elem may not have been initialized - The constructor Element(Element) is undefined

Because

Element elem;

could be null when

list.removeFirst(elem);

is executed.

So it will be

Element elem = null;

(You need to initialize it to use it.)

Anyway, i'm pretty sure you want something like this:

list.addFirst(elem = new Element(name,number));

So it

list.removeFirst(elem);

will remove the item added recently.

Anyway, are you sure you don't want to use removeFirstOccurrence ? Because removeFirst does a total different thing.

removeFirstOccurrence :

Removes the first occurrence of the specified element in this list (when traversing the list from head to tail). If the list does not contain the element, it is unchanged.

Anyway the reason you get this error, is not related to the recursion

Edit :

Well, you don't need any edit to addFirst since removeFirst will remove the first item in the list. You just need to change

removeFirst(elem);

to

removeFirst();

In this case, if you don't use it in other places, you don't need anymore elem .

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