-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergesortForLinkedLists.cpp
More file actions
92 lines (88 loc) · 1.46 KB
/
MergesortForLinkedLists.cpp
File metadata and controls
92 lines (88 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
typedef struct node node;
void push(node **head,int data)
{
node *temp=new node;
temp->data=data;
temp->next=(*head);
(*head)=temp;
}
void printList(node *head)
{
node *curr=head;
while(curr!=NULL)
{
cout<<curr->data<<" ";
curr=curr->next;
}
}
int getCount(node *head1)
{
int cnt=0;
node *curr=head1;
while(curr!=NULL)
{
cnt++;
curr=curr->next;
}
return cnt;
}
node *mergeList(node *head1,node *head2)
{
node *res=NULL;
if(head1==NULL)
return head2;
if(head2==NULL)
return head1;
if(head1->data > head2->data)
{
res=head2;
res->next=mergeList(head1,head2->next);
}
else
{
res=head1;
res->next=mergeList(head1->next,head2);
}
return res;
}
node *mergesort(node *a)
{
node *oldhead=a;
int mid=getCount(a)/2;
if(a->next==NULL)
return a;
while((mid-1)>0)
{
oldhead=oldhead->next;
mid--;
}
node *newHead=oldhead->next;
oldhead->next=NULL;
oldhead=a;
node *l1=mergesort(oldhead);
node *l2=mergesort(newHead);
return mergeList(l1,l2);
}
int main()
{
node *head1=NULL;
node *res=NULL;
push(&head1,15);
push(&head1,10);
push(&head1,5);
push(&head1,20);
push(&head1,3);
push(&head1,2);
res=mergesort(head1);
printList(res);
return 0;
}