Question: public class Code2{ static class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } static Node mergeLists(Node

public class Code2{

static class Node { int data; Node next;

Node(int data) { this.data = data; this.next = null; } }

static Node mergeLists(Node head1, Node head2) { Node dummy = new Node(0); Node current = dummy;

while (head1 != null && head2 != null) { if (head1.data < head2.data) { current.next = head1; head1 = head1.next; } else if (head1.data > head2.data) { current.next = head2; head2 = head2.next; } else { // Add only one instance of duplicate values current.next = head1; head1 = head1.next; head2 = head2.next; } current = current.next; }

// Append remaining elements from either list if (head1 != null) { current.next = head1; } else { current.next = head2; }

return dummy.next; }

static void printList(Node head) { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); }

public static void main(String[] args) { Node head1 = new Node(1); head1.next = new Node(3); head1.next.next = new Node(5); head1.next.next.next = new Node(7); head1.next.next.next.next = new Node(9);

Node head2 = new Node(2); head2.next = new Node(4); head2.next.next = new Node(6); head2.next.next.next = new Node(8); head2.next.next.next.next = new Node(10);

Node mergedHead = mergeLists(head1, head2); printList(mergedHead); } }Analyze the code in detail

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!