I am trying to implement LinkedList using Java, just to test my skills. I am stuck in one problem where I need to add two linked lists that I created. I get into an endless cycle. Is there a way to improve the code and implement the desired result?
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()); } }
user1655719
source share