You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When a head node of Linked-List is given, sort this linked list.
This linked-list is un-ordered.
Approach
Basic concept of solution is merge sort.
Two pointers trick is used to divide to left-side, right-side.
functionmergeSort(node){if(node===null)returnnull;letslow=node;letfast=node;// O O// S// O-O-O// S F// O-O-O-O// S F// O-O-O-O-O// S F// O-O-O O-O-O// S F// O-O-O-O O-O-O-O// S F// O-O-O-O-O O-O-O-O-O// S Fwhile(fast.next&&fast.next.next){slow=slow.next;fast=fast.next.next;}if(slow===node&&node.next){if(node.val<node.next.val){returnnode;}else{constnext=node.next;node.next=null;next.next=node;returnnext;}}elseif(slow===node&&!node.next){returnnode;}// O-O-O-O// S Fconsttemp=slow.next;slow.next=null;letleftStart=mergeSort(node);letrightStart=mergeSort(temp);returnmerge(leftStart,rightStart);}functionmerge(leftStart,rightStart){constdummy=newListNode(0);letcurrent=dummy;while(leftStart&&rightStart){if(leftStart.val<rightStart.val){current.next=leftStart;leftStart=leftStart.next;}else{current.next=rightStart;rightStart=rightStart.next;}current=current.next}if(leftStart){current.next=leftStart;}if(rightStart){current.next=rightStart;}returndummy.next;}
The text was updated successfully, but these errors were encountered:
Problem
When a head node of Linked-List is given, sort this linked list.
This linked-list is un-ordered.
Approach
Basic concept of solution is merge sort.
Two pointers trick is used to divide to left-side, right-side.
The text was updated successfully, but these errors were encountered: