I am looking for help with a homework assignment that requires us to merge two linked list (integer type) and create a third list that is sorted without destroying the original list. I have created the code to get my first two linked list to display, and have the start of my merger method, but have hit a wall probably because of over thinking. I was hoping there was some easy way to append one linked list to another, but have had no such luck attempting this. A note on any assistance provided, please avoid using structs and pointers as we haven't really gotten into those yet and i don't feel at all confident with using them here especially since I'm still trying to figure out this whole linked list idea. Thank you in advance, and please try and edit my own code so it is easier for me to follow. Thanks.
package hw3_vinson; import javax.xml.*; public class HW3_Vinson { public static void main(String[] args) { //Linked list one holding integers HW3_Vinson LL1 = new HW3_Vinson(); LL1.add(1); LL1.add(3); LL1.add(2); //Linked list two holding integers HW3_Vinson LL2 = new HW3_Vinson(); LL2.add(4); LL2.add(8); LL2.add(5); //Will hold combination of LL1 and LL2 HW3_Vinson LL3 = new HW3_Vinson(); //Print each list LL1.print(); LL2.print(); LL3.print(); } //Node Class creation private class Node { int element; Node next; Node(int el, Node n) { element = el; next = n; } Node(int el) { this(el, null); } } //Set up nodes to store first and last element private Node firstElement; private Node lastElement; //Constructor for class public HW3_Vinson() { firstElement = null; lastElement = null; } //check to see if list is empty, return null if true public boolean isEmpty() { return firstElement == null; } //add to end of list public void add(int e) { if (isEmpty()) { firstElement = new Node(e); lastElement = firstElement; } else { lastElement.next = new Node(e); lastElement = lastElement.next; } } //Combine two linked list and return a new linked list NOTE: This code does not work, and I know that I can't //use the .add method because it is for adding integers to a linked list. I had tried to create another addList method //but got no where with it. /* public Node mergeList(Node L1, Node L2) { Node LL1 = L1; Node LL2 = L2; Node LL3 = null; while (LL1 != null) { LL3.add(LL1); } while (LL2 != null) { LL3.add(LL2); } return LL3; } */ //Print out linked list public void print() { Node ref = firstElement; while (ref != null) { System.out.println(ref.element + " "); ref = ref.next; } } }