#include <bits/stdc++.h>
using
namespace
std;
class
node {
public
:
int
data;
node* next;
node(
int
d)
{
data = d;
next = NULL;
}
};
void
insert_at_head(node*& head,
int
data)
{
node* n =
new
node(data);
n->next = head;
head = n;
return
;
}
void
print(node* head)
{
while
(head != NULL) {
cout << head->data <<
" "
;
head = head->next;
}
cout << endl;
return
;
}
node* merge_alternate(node* head1, node* head2)
{
if
(head2)
head2 = head2->next;
node* head3 = NULL;
node* cur = NULL;
if
(head1)
head3 = head1;
else
head3 = head2;
while
(head1 != NULL && head2 != NULL) {
if
(cur)
cur->next = head1;
cur = head1;
if
(head1->next != NULL)
head1 = head1->next->next;
else
head1 = NULL;
cur->next = head2;
cur = head2;
if
(head2->next != NULL)
head2 = head2->next->next;
else
head2 = NULL;
}
while
(head1 != NULL) {
if
(cur)
cur->next = head1;
cur = head1;
if
(head1->next != NULL)
head1 = head1->next->next;
else
head1 = NULL;
}
while
(head2 != NULL) {
if
(cur)
cur->next = head2;
cur = head2;
if
(head2->next != NULL)
head2 = head2->next->next;
else
head2 = NULL;
}
if
(cur)
cur->next = NULL;
return
head3;
}
int
main()
{
node *head1 = NULL, *head2 = NULL;
insert_at_head(head1, 6);
insert_at_head(head1, 19);
insert_at_head(head1, 13);
insert_at_head(head1, 12);
insert_at_head(head1, 10);
insert_at_head(head1, 5);
insert_at_head(head1, 1);
insert_at_head(head2, 9);
insert_at_head(head2, 7);
insert_at_head(head2, 2);
head1 = merge_alternate(head1, head2);
print(head1);
}