Advertisement
satishfrontenddev4

Untitled

Jan 5th, 2024
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Given a singly linked list containing N integers, sort it in O(NlogN) time.
  3.  
  4. Input format
  5. N - An integer denoting the number of nodes in the linked list.
  6.  
  7. N integers follow where ith integer denotes the ith node value in the linked list-
  8.  
  9. Output format
  10. Return the head of the sorted list.
  11.  
  12. Function definition
  13. You have to implement the given function. It accepts the head of the LL as an argument. You have to return the new head of the sorted list after sorting it
  14.  
  15. Constraints
  16. 0 <= N <= 10^5
  17.  
  18. -10^9 <= value <= 10^9
  19.  
  20. Sample Input 1
  21. 4
  22.  
  23. 4 2 1 3
  24.  
  25. Sample Output 1
  26. 1 2 3 4
  27.  
  28. Explanation 1
  29. This is the sorted output.
  30.  
  31. Sample Input 2
  32. 4
  33.  
  34. 8 20 2 9
  35.  
  36. Sample Output 2
  37. 2 8 9 20
  38.  
  39. Explanation 2
  40. This is the sorted output.
  41. */
  42.  
  43. /*
  44. class ListNode{
  45.     constructor(val){
  46.         this.val = val;
  47.         this.next = null;
  48.     }
  49. */
  50.  
  51. /**
  52.  * @param {ListNode} head
  53.  * @return {ListNode}
  54.  */
  55. function sortList(head) {
  56.       let arr=[];
  57.       let pointer=head;
  58.       while(pointer!=null){
  59.             arr.push(pointer.val);
  60.             pointer=pointer.next;
  61.       }
  62.       arr. sort((a,b)=>a-b);
  63.       let i=0;
  64.       pointer=head;
  65.       while(pointer!=null){
  66.             pointer.val=arr[i];
  67.             i++;
  68.             pointer=pointer.next;
  69.       }
  70.  
  71.  
  72.       return head;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement