-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergesort2linkedlist.txt
45 lines (37 loc) · 1.04 KB
/
mergesort2linkedlist.txt
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
#include <bits/stdc++.h>
/************************************************************
Following is the linked list node structure.
template <typename T>
class Node {
public:
T data;
Node* next;
Node(T data) {
next = NULL;
this->data = data;
}
~Node() {
if (next != NULL) {
delete next;
}
}
};
************************************************************/
Node<int>* sortTwoLists(Node<int>* list1, Node<int>* list2)
{
// Write your code here.
if(!list1){return list2;}
if(!list2){return list1;}
if(list1->data>list2->data){swap(list1,list2);}
Node<int> *res=list1;
while(list1!=NULL && list2!=NULL){
Node<int> *temp=NULL;
while(list1!=NULL && list1->data<=list2->data){
temp=list1;
list1=list1->next;
}
temp->next=list2;
swap(list1,list2);
}
return res;
}