The Java code provided demonstrates how to merge two linked lists by alternating their nodes.
Note: The merging operation demonstrated in this code alternates the nodes of the two linked lists, effectively merging them. However, this approach assumes that the two linked lists are of the same length. If the linked lists have different lengths, the merging result may not be as expected. Additional handling may be required to properly merge linked lists of different lengths.
class Merge_LinkedList { Node head; class Node { String data; Node next; Node(String d) { data = d; next = null; } } void push(String new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } void merge(Merge_LinkedList q) { Node p_curr = head, q_curr = q.head; Node p_next, q_next; while (p_curr != null && q_curr != null) { p_next = p_curr.next; q_next = q_curr.next; q_curr.next = p_next; p_curr.next = q_curr; p_curr = p_next; q_curr = q_next; } q.head = q_curr; } void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data+" "); temp = temp.next; } System.out.println(); } public static void main(String args[]) { Merge_LinkedList col1 = new Merge_LinkedList(); Merge_LinkedList col2 = new Merge_LinkedList(); col1.push("Red"); col1.push("Pink"); col1.push("Orange"); System.out.println("First Linked List.."); col1.printList(); col2.push("Blue"); col2.push("Yellow"); col2.push("Green"); col2.push("White"); col2.push("Black"); System.out.println("Second Linked List.."); col1.merge(col2); System.out.println("Modified First Linked List.."); col1.printList(); System.out.println("Modified Second Linked List.."); col2.printList(); } }
First Linked List.. Orange Pink Red Second Linked List.. Modified First Linked List.. Orange Black Pink White Red Green Modified Second Linked List.. Yellow Blue
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions