Open In App

Python Program To Merge A Linked List Into Another Linked List At Alternate Positions

Last Updated : 17 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Python3




# Python program to merge a linked list 
# into another at alternate positions
class Node(object):
    def __init__(self, data:int):
        self.data = data
        self.next = None
  
class LinkedList(object):
    def __init__(self):
        self.head = None
          
    def push(self, new_data:int):
        new_node = Node(new_data)
        new_node.next = self.head
  
        # 4. Move the head to point to 
        # new Node
        self.head = new_node
          
    # Function to print linked list from 
    # the Head
    def printList(self):
        temp = self.head
        while temp != None:
            print(temp.data)
            temp = temp.next
              
    # Main function that inserts nodes of linked 
    # list q into p at alternate positions. 
    # Since head of first list never changes
    # but head of second list/ may change, 
    # we need single pointer for first list and 
    # double pointer for second list.
    def merge(self, p, q):
        p_curr = p.head
        q_curr = q.head
  
        # swap their positions until one 
        # finishes off
        while p_curr != None and q_curr != None:
  
            # Save next pointers
            p_next = p_curr.next
            q_next = q_curr.next
  
            # make q_curr as next of p_curr
            # change next pointer of q_curr
            q_curr.next = p_next  
  
            # change next pointer of p_curr
            p_curr.next = q_curr  
  
            # update current pointers for next 
            # iteration
            p_curr = p_next
            q_curr = q_next
            q.head = q_curr
  
# Driver code
llist1 = LinkedList()
llist2 = LinkedList()
  
# Creating Linked lists
# 1.
llist1.push(3)
llist1.push(2)
llist1.push(1)
llist1.push(0)
  
# 2.
for i in range(8, 3, -1):
    llist2.push(i)
  
print("First Linked List:")
llist1.printList()
  
print("Second Linked List:")
llist2.printList()
  
# Merging the LLs
llist1.merge(p=llist1, q=llist2)
  
print("Modified first linked list:")
llist1.printList()
  
print("Modified second linked list:")
llist2.printList()
  
# This code is contributed by Deepanshu Mehta


Output: 

First Linked List:
1 2 3
Second Linked List:
4 5 6 7 8
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 a linked list into another linked list at alternate positions for more details!



Similar Reads

C++ Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of second list into first list at alternate positions of 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 se
3 min read
C Program To Merge A Linked List Into Another Linked List At Alternate Positions
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
3 min read
Java Program To Merge A Linked List Into Another Linked List At Alternate Positions
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
3 min read
Javascript Program To Merge A Linked List Into Another Linked List At Alternate Positions
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
3 min read
Merge a linked list into another linked list at alternate positions
Given two linked lists, insert nodes of second list into first list at alternate positions of 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 se
11 min read
Number of sequences which has HEAD at alternate positions to the right of the first HEAD
Given that a coin is tossed N times. The task is to find the total number of the sequence of tosses such that after the first head from left, all the alternating positions to the right of it are occupied by the head only. The positions except the alternating position can be occupied by any of head or tail. For example, if you are tossing a coin 10
6 min read
Insert a linked list into another linked list
Given two linked lists, list1 and list2 of sizes m and n respectively. The task is to remove list1's nodes from the ath node to the bth node and insert the list2 in their place.Examples: Input: list1: 10->11->12->13->14->15, list2: 100->101->102->103, a = 3, b = 4Output: 10->11->12->100->101->102->103->1
13 min read
Merge an array of size n into another array of size m+n
There are two sorted arrays. First one is of size m+n containing only m elements. Another one is of size n and contains n elements. Merge these two arrays into the first array of size m+n such that the output is sorted. Input: array with m+n elements (mPlusN[]). NA => Value is not filled/available in array mPlusN[]. There should be n such array
12 min read
Python Program For Reversing Alternate K Nodes In A Singly Linked List
Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm. Example: Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3 Output: 3->2->1->4->5->6->9->8->7->NULL. Method 1 (Process 2k node
6 min read
Python Program For Arranging Single Linked List In Alternate Odd and Even Nodes Order
Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where the first node is even, second odd, third even an
7 min read
Practice Tags :
three90RightbarBannerImg