Merge a linked list into another linked list at alternate positions leetcode


Given two linked lists, insert nodes of second list into first list at alternate positions of first list.

void merge(struct node *p,struct node **q)
{
struct node *p_curr = p, *q_curr = *q;
struct node *p_next, *q_next;
// While therre are avialable positions in p
while (p_curr != NULL && q_curr != NULL)
{
// Save next pointers
p_next = p_curr->next;
q_next = q_curr->next;
// Make q_curr as next of p_curr
q_curr->next = p_next;// Change next pointer of q_curr
p_curr->next = q_curr;// Change next pointer of p_curr
// Update current pointers for next iteration
p_curr = p_next;
q_curr = q_next;
}
*q = q_curr;// Update head pointer of second list
}
Read full article from Merge a linked list into another linked list at alternate positions | GeeksforGeeks