Advertisement
satishfrontenddev4

Untitled

Jan 5th, 2024
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Given a singly linked list, find the middle node of the linked list and move that node to the head of the list. Return the head of the list. In the case of a list with an even number of nodes, use the second middle one.
  3.  
  4. Input format
  5. There are 2 lines of input
  6.  
  7. N - An integer denoting the number of nodes in the linked list.
  8.  
  9. N integers follow where ith integer denotes the ith node value in the linked list
  10.  
  11. Output format
  12. Return the head of the modified list after moving the middle node to head.
  13.  
  14. Constraints
  15. 0 <= N<= 10^5
  16.  
  17. -10^9 <= value <= 10^9
  18.  
  19. Sample Input 1
  20. 6
  21.  
  22. 2 3 4 5 6 7
  23.  
  24. Sample Output 1
  25. 5 2 3 4 6 7
  26.  
  27. Explanation 1
  28. The middle node here is [5]. Moving that to the head of the list gives us the output shown.
  29.  
  30. Sample Input 2
  31. 5
  32.  
  33. 1 2 3 4 5
  34.  
  35. Sample Output 2
  36. 3 1 2 4 5
  37.  
  38. Explanation 2
  39. The middle node here is [3]. Moving that to the head of the list gives us the output shown.
  40. */
  41.  
  42. /*
  43. class ListNode{
  44.     constructor(val){
  45.         this.val = val;
  46.         this.next = null;
  47.     }
  48. */
  49. /**
  50.  * @param {ListNode} head
  51.  * @return {ListNode}
  52.  */
  53. function moveMiddleToHead(head) {
  54.       let slow, slow_prev,fast;
  55.       slow=head;
  56.       slow_prev=null;
  57.       fast=head;
  58.       if(head==null||head.next==null)
  59.       return head;
  60.       // let count=0;
  61.       while(slow!=null&&fast!=null){
  62.             if(fast.next==null)
  63.                   break;
  64.             // count++;
  65.             slow_prev=slow;
  66.             slow=slow.next;
  67.             fast=fast.next.next;
  68.       }
  69.       // console.log("iteration count=",count);
  70.       // console.log("slow.val",slow.val)
  71.       // console.log("slow.next.val=",slow.next.val);
  72.       // console.log("slow_prev",slow_prev.val)
  73.       // console.log("fast",fast.val)
  74.       let slow_next=slow.next;
  75.       slow.next=head;
  76.       slow_prev.next=slow_next;
  77.       head=slow;
  78.       return head;
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement