In: Computer Science
(Java)
Create a new linked list from two given arrays with the greater
element from each corresponding array element placed into the
linked list.
Given two arrays of varying size initialized with integers of
varying values, the task is to create a new linked list using those
arrays. The condition is that the greater element value from each
corresponding array element will be added to the new linked list in
the list position that maintains the integers in ascending order.
When the program has reached the end of the shorter array, the
remaining elements of the longer array will be added to the linked
list in such a way as to maintain the integers in the linked list
in ascending order.
Java code:
public class LinkedList { Node head = null; static class Node { public int value; public Node next; public Node(int value) { this.value = value; this.next = null; } } public static void main(String[] args) { int[] a1 = {2, 5, 3, 9, 11}; int[] a2 = {5, 67, 33, 0, 7, 9, 4}; LinkedList list = new LinkedList(); int ind1 = 0, ind2 = 0; while (ind1 < a1.length && ind2 < a2.length) { if (a1[ind1] >= a2[ind2]) { list.add(a1[ind1]); } else list.add(a2[ind2]); ind1++; ind2++; } //Adding left over nodes if any for (; ind1 < a1.length; ind1++) list.add(a1[ind1]); for (; ind2 < a2.length; ind2++) list.add(a2[ind2]); list.display(); } /** * * @param val Adds the value in appropriate position in the list */ public void add(int val) { Node curr = head; if (curr == null) { head = new Node(val); return; } if(val<head.value) { Node n = new Node(val); n.next = head; head = n; return; } Node prev = null; while (curr != null && curr.value < val) { prev = curr; curr = curr.next; } if (curr != null) { Node temp = curr; prev.next = new Node(val); prev.next.next = temp; } else { prev.next = new Node(val); } } /** * Prints the numbers in list */ public void display() { Node curr = head; while (curr != null) { System.out.println(curr.value + " "); curr = curr.next; } } }
Output:
4
5
9
9
11
33
67
Please let me know if any tweaks are requried. If not, do give a
thumbs up