#include <bits/stdc++.h>
using
namespace
std;
struct
Node {
int
data;
struct
Node* next;
};
Node* getNode(
int
data)
{
Node* newNode = (Node*)
malloc
(
sizeof
(Node));
newNode->data = data;
newNode->next = NULL;
return
newNode;
}
void
FrontBackSplit(Node* source,
Node** frontRef, Node** backRef)
{
Node* fast;
Node* slow;
if
(source == NULL || source->next == NULL) {
*frontRef = source;
*backRef = NULL;
}
else
{
slow = source;
fast = source->next;
while
(fast != NULL) {
fast = fast->next;
if
(fast != NULL) {
slow = slow->next;
fast = fast->next;
}
}
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
}
}
Node* SortedMerge(Node* a, Node* b)
{
Node* result = NULL;
if
(a == NULL)
return
b;
else
if
(b == NULL)
return
a;
if
(a->data <= b->data) {
result = a;
result->next = SortedMerge(a->next, b);
}
else
{
result = b;
result->next = SortedMerge(a, b->next);
}
return
result;
}
void
MergeSort(Node** headRef)
{
Node* head = *headRef;
Node *a, *b;
if
((head == NULL) || (head->next == NULL))
return
;
FrontBackSplit(head, &a, &b);
MergeSort(&a);
MergeSort(&b);
*headRef = SortedMerge(a, b);
}
static
void
reverse(Node** head_ref)
{
Node* prev = NULL;
Node* current = *head_ref;
Node* next;
while
(current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
void
alternateMerge(Node* head1, Node* head2)
{
Node *p, *q;
while
(head1 != NULL && head2 != NULL) {
p = head1->next;
head1->next = head2;
head1 = p;
q = head2->next;
head2->next = head1;
head2 = q;
}
}
Node* altSortForLinkedList(Node* head)
{
MergeSort(&head);
Node *front, *back;
FrontBackSplit(head, &front, &back);
reverse(&back);
alternateMerge(front, back);
return
front;
}
void
printList(Node* head)
{
while
(head != NULL) {
cout << head->data <<
" "
;
head = head->next;
}
}
int
main()
{
Node* head = getNode(10);
head->next = getNode(9);
head->next->next = getNode(8);
head->next->next->next = getNode(7);
head->next->next->next->next = getNode(6);
head->next->next->next->next->next = getNode(5);
cout <<
"Original list: "
;
printList(head);
head = altSortForLinkedList(head);
cout <<
"\nModified list: "
;
printList(head);
return
0;
}