I am trying to implement LinkedList using Java, just to test my skills. I am stuck at one problem, where I have to append two linked lists that I have created. I get into an infinite loop here. Is there any way I can improve the code and implement the desired output ?
I/Ps :
List A : 4->3->2->1->0
List B : 4->3->2->1->0
O/P should be : 4->3->2->1->0->4->3->2->1->0
class List {
int val;
List next;
public List(int val) {
this.val = val;
}
public String toString() {
String output = "";
List current = this;
while (current != null) {
output += current.val + "->";
current = current.next;
}
return output + "NULL";
}
}
class AppendLinkedLists {
static List push(List list, int num) {
List newList = new List(num);
newList.next = list;
return newList;
}
static List appendLists(List listA, List listB) {
if (listA == null)
return listB;
else {
List tempList = listA;
while (tempList.next.next != null) {
tempList = tempList.next;
}
tempList.next.next = listB;
return listA;
}
}
public static void main(String[] args) {
List listA = new List(0);
listA = push(listA, 1);
listA = push(listA, 2);
listA = push(listA, 3);
listA = push(listA, 4);
List listB = listA;
System.out.println("Input List A : " + listA.toString());
System.out.println("Input List B : " + listB.toString());
listA = appendLists(listA, listB);
System.out.println("Combined Input Lists A and B : " + listA.toString());
}
}
You don’t have 2 lists. You only have one.
assigns the reference
listBto point tolistA. So you’re appendinglistAonto itself.Regardless of what other issues you have, I would correct this (the simplest way being to create a
listBin a similar fashion to how you’ve createdlistA).My other comment (hope you don’t mind) is that you’ve created a List object, but it has little/no behaviour of its own. Instead of creating your
AppendLinkedListsclass, I would put the functionality into theListobject e.g. instead of:write:
etc. So the behaviour is encapsulated within the
Listobject. Similarly you could then write:by making use of overloading.