But sir if A = 1->2->2->2->3->3 and B = 2->2->2->2->2->2=3 then your ans returns 1->2->2->2->2->2->3->3 but the union of these two set is 1->2->3. SImply it does not take care of repeating values.
@Prince-yz1tc4 жыл бұрын
Why we have made a object of Node class temp? How it is preventing from null pointer exception.?
@CodingSimplified4 жыл бұрын
We made temp as object of Node class, so that we keep appending the smaller value in it & at last we can return the finalList.next. - Now if you don't want to create temp as new Object & use, that's also fine. Just that you need to update the code as following:. Updating the code in mergeWithUnion. You'll need a head & temp to operate this one: private Node mergeWithUnion(Node a, Node b) { Node head, temp; head = temp = null; while(a != null && b != null) { if(a.data < b.data) { if(head == null) { head = temp = a; } else { temp.next = a; temp = temp.next; } a = a.next; } else if(a.data > b.data) { if(head == null) { head = temp = b; } else { temp.next = b; temp = temp.next; } b = b.next; } else { if(head == null) { head = temp = a; } else { temp.next = a; temp = temp.next; } a = a.next; b = b.next; } } temp.next = (a == null) ? b : a; return head; } Let me know if it looks fine to you or if you've any further questions.
@amiransari35643 жыл бұрын
Hi , I run this code and returning wrong union values. Please could you check below input List1: 9 6 4 2 3 8 List2: 1 2 8 6 2 Output: 1 2 2 3 4 6 8 9