I have written copy() method to copy the data of one linked list to another. However, i am not able to get the output i really need help on this. i really need to know where the error is as the issue is its not displaying the output:
public class Link
{
public int iData; // data item
public Link next; // next link in list
// -------------------------------------------------------------
public Link(int id) // constructor
{
iData = id;
}
// -------------------------------------------------------------
public void displayLink() // display ourself
{
System.out.print("{" + iData +"}");
}
} // end of class
public class LinkList
{
private Link first; // reference to first link on list
private Link last; // REFERENCE TO LAST LINK ON LIST
// -------------------------------------------------------------
public LinkList() // constructor
{
first = null; // no items on list yet
}
// -------------------------------------------------------------
public boolean isEmpty() // true if list is empty
{
return (first==null);
}
// -------------------------------------------------------------
// insert at start of list
public void insertFirst(int id)
{
Link newLink = new Link(id);
newLink.next = first; // newLink --> old first
first = newLink; // first --> newLink
}
// -------------------------------------------------------------
public LinkList copy()
{
LinkList L5 =new LinkList();
Link current= first;
int x;
while(current!=null) // i think something is wrong here
{
x=current.iData;
L5.insertFirst(x);
current=current.next;
}
return L5;
}
public static void main(String[] args)
{
LinkList L1 = new LinkList(); // make new list
L1.insertFirst(22); // insert four items
L1.insertFirst(44);
L1.insertFirst(66);
L1.insertFirst(88);
L1.insertFirst(99);
L1.displayList(); // display list
LinkList Lcopy=new LinkList();
System.out.println("-----------------Copied data in new list is:------------");
Lcopy.copy();
Lcopy.displayList();
}
}
the output is :
List (first-->last): {99}{88}{66}{44}{22}
-----------------Copied data in new list------------
List (first-->last):
the values are not getting copied to another linked list.