-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked List that is Sorted Alternatingly
59 lines (57 loc) · 1.31 KB
/
Linked List that is Sorted Alternatingly
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
class Solution
{
public:
// your task is to complete this function
Node* reverse(Node *head)
{
Node *prevPtr=NULL;
Node *currPtr=head;
Node *nextPtr;
while(currPtr!=nullptr)
{
nextPtr=currPtr->next;
currPtr->next=prevPtr;
prevPtr=currPtr;
currPtr=nextPtr;
}
return prevPtr;
}
Node* merge(Node *l1, Node *l2)
{
Node *dummy=new Node(-1);
Node *tail=dummy;
while(l1 && l2)
{
if(l1->data<l2->data)
{
tail->next=l1;
l1=l1->next;
}
else{
tail->next=l2;
l2=l2->next;
}
tail=tail->next;
}
tail->next=l1?l1:l2;
return dummy->next;
}
void sort(Node **head)
{
// Code here
Node *odd=(*head);
Node *even=(*head)->next;
Node *evenStart=even;
while(even->next!=nullptr)
{
odd->next=even->next;
odd=odd->next;
even->next=odd->next;
if(odd->next!=nullptr)
even=even->next;
}
odd->next=nullptr;
Node *newHead=reverse(evenStart);
(*head)=merge(*head,newHead);
}
};