Skip to content

Commit

Permalink
Merge pull request #472 from Tech-neophyte/patch-5
Browse files Browse the repository at this point in the history
day 22-q3 (py3, cpp) solution added #440
  • Loading branch information
bh-g authored Jan 24, 2024
2 parents 6deedcc + 37cbde4 commit e24a3d6
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions Day-22/q3: Sort List/Tech-neophyte--cp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
## Cpp code: merge sort
```
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
/// Merge Function
ListNode *mergeList(ListNode *l1, ListNode *l2){
ListNode *prev=new ListNode(-1), *curr=prev;
while(l1 and l2){
if(l1->val<=l2->val){
curr->next=l1;
l1=l1->next;
}else{
curr->next=l2;
l2=l2->next;
}
curr=curr->next;
}
if(l1){
curr->next=l1;
l1=l1->next;
}
if(l2){
curr->next=l2;
l2=l2->next;
}
return prev->next;
}
/// Divide and Conquer Approach (Merge Sort)
ListNode* sortList(ListNode* head){
if(!head or !head->next) return head;
ListNode *slow=head, *fast=head, *temp=NULL;
while(fast and fast->next){
temp=slow;
slow=slow->next;
fast=fast->next->next;
}
temp->next=NULL;
ListNode *point1=sortList(head), *point2=sortList(slow);
return mergeList(point1,point2);
}
};
```
## Python code: (Using lists)
```
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
curr = head
l =[]
while curr:
l.append(curr.val)
curr = curr.next
l.sort()
curr = head
for i in l:
curr.val = i
curr = curr.next
return head
```

0 comments on commit e24a3d6

Please sign in to comment.