0

I am trying to add a linkedlist to another linkedlist using a method called addList in the MyLinkedList class. What I'm stuck on is how to implement the method so that I can add a linkedlist to another linkedlist of index location of my choosing.

Here's what I have in MyLinkedList:

public void addList(int index, E e){
 if(index == 0){
 addFirst(e);
 } else if (index >= size){
 addLast(e);
 }
 else{
 Node<E> current = head;
 for(int i = 1; i < index; i++){
 current = current.next;
 }
 Node<E> temp = current.next;
 current.next = new Node<E>(e);
 (current.next).next = temp;
 size++;
 }
}

I know this method won't work, I've tried it. In my program itself, I have these:

public class linkedlistwork {
 public static void main(String[] args) {
 MyLinkedList<String> alpha = new MyLinkedList<String>();
 alpha.add("hello");
 alpha.add("world");
 alpha.add("this");
 System.out.println(alpha);
 MyLinkedList<String> beta = new MyLinkedList<String>();
 beta.add("is");
 beta.add("java");
 beta.add("rocks");
 System.out.println(beta);
 alpha.addList(1, beta);
 System.out.println(alpha);
 }
}

The correct output would be something like:

OUTPUT:
[hello, is, java, rocks, world, this]

My program would not run, an error occurred in this line

alpha.addList(1, beta);

on the "beta" part, it says:

method addList in class MyLinkedList cannot be applied to given types; required: int,String found: int,MyLinkedList reason: actual argument MyLinkedList cannot be converted to String by method invocation conversion where E is a type-variable: E extends Object declared in class MyLinkedList

How would I fix my method so that I can use it correctly? Thanks in advance!!

asked Nov 15, 2012 at 23:18
2
  • Can you please add in vector definitions? Commented Nov 15, 2012 at 23:21
  • I think you'll need your addList method to have the generic in there: public void <E> addList(int index, E e) { Commented Nov 15, 2012 at 23:21

2 Answers 2

2

It appears to me that your addList method signature is the problem. It should look like:

public void addList(int index, List<E> list)
answered Nov 15, 2012 at 23:22
0
1

You need to have a method for adding MyLinkedList<String>. Something like this would do

public void addList(int index, MyLinkedList<E> beta){
//Somehow loop through the MyLinkedList, and do this.
 add(index+i,beta(i));
}
answered Nov 15, 2012 at 23:23
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.