Reputation: 23
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!!
Upvotes: 0
Views: 1441
Reputation: 39698
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));
}
Upvotes: 1
Reputation: 51
It appears to me that your addList method signature is the problem. It should look like:
public void addList(int index, List<E> list)
Upvotes: 2