Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given a singly linked list containing N integers, sort it in O(NlogN) time.
- Input format
- N - An integer denoting the number of nodes in the linked list.
- N integers follow where ith integer denotes the ith node value in the linked list-
- Output format
- Return the head of the sorted list.
- Function definition
- 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
- Constraints
- 0 <= N <= 10^5
- -10^9 <= value <= 10^9
- Sample Input 1
- 4
- 4 2 1 3
- Sample Output 1
- 1 2 3 4
- Explanation 1
- This is the sorted output.
- Sample Input 2
- 4
- 8 20 2 9
- Sample Output 2
- 2 8 9 20
- Explanation 2
- This is the sorted output.
- */
- /*
- class ListNode{
- constructor(val){
- this.val = val;
- this.next = null;
- }
- */
- /**
- * @param {ListNode} head
- * @return {ListNode}
- */
- function sortList(head) {
- let arr=[];
- let pointer=head;
- while(pointer!=null){
- arr.push(pointer.val);
- pointer=pointer.next;
- }
- arr. sort((a,b)=>a-b);
- let i=0;
- pointer=head;
- while(pointer!=null){
- pointer.val=arr[i];
- i++;
- pointer=pointer.next;
- }
- return head;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement