Java Program To Merge A Linked List Into Another Linked List At Alternate Positions
Last Updated :
14 Dec, 2022
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list.
For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The nodes of the second list should only be inserted when there are positions available. For example, if the first list is 1->2->3 and the second list is 4->5->6->7->8, then the first list should become 1->4->2->5->3->6 and the second list to 7->8.
Use of extra space is not allowed (Not allowed to create additional nodes), i.e., insertion must be done in-place. The expected time complexity is O(n) where n is the number of nodes in the first list.
The idea is to run a loop while there are available positions in first loop and insert nodes of second list by changing pointers. Following are implementations of this approach.
Java
public class LinkedList
{
Node head;
class Node
{
int data;
Node next;
Node( int d)
{
data = d;
next = null ;
}
}
void push( int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
void 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[])
{
LinkedList llist1 =
new LinkedList();
LinkedList llist2 =
new LinkedList();
llist1.push( 3 );
llist1.push( 2 );
llist1.push( 1 );
System.out.println(
"First Linked List:" );
llist1.printList();
llist2.push( 8 );
llist2.push( 7 );
llist2.push( 6 );
llist2.push( 5 );
llist2.push( 4 );
System.out.println(
"Second Linked List:" );
llist1.merge(llist2);
System.out.println(
"Modified first linked list:" );
llist1.printList();
System.out.println(
"Modified second linked list:" );
llist2.printList();
}
}
|
Output
First Linked List:
1 2 3
Second Linked List:
Modified first linked list:
1 4 2 5 3 6
Modified second linked list:
7 8
Time Complexity: O(N)
Auxiliary Space: O(1)
Please refer complete article on Merge linked list into another linked list at alternate positions for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...