Advertisement
satishfrontenddev4

Untitled

Jan 5th, 2024
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.
  3.  
  4. The first node is considered odd, and the second node is even, and so on.
  5.  
  6. Note that the relative order inside both the even and odd groups should remain as it was in the input.
  7.  
  8. Input format
  9. First line contains an integer N - Number of nodes in the linked list.
  10.  
  11. Second line contains N integers representing the linked list.
  12.  
  13. Output format
  14. Return the head of the reordered linked list.
  15.  
  16. Sample Input 1
  17. 5
  18.  
  19. 1 5 3 4 8
  20.  
  21. Sample Output 1
  22. 1 3 8 5 4
  23.  
  24. Explanation
  25. Arranging the odd nodes first i.e. 1st, 3rd, 5th node and then the even nodes i.e. 2nd, 4th will give us 1, 3, 8, 5, 4.
  26.  
  27. Constraints
  28. 0 <= N <= 10^5
  29.  
  30. -10^9 <= Value of node <= 10^9
  31. */
  32.  
  33. /*
  34. class ListNode{
  35.     constructor(val){
  36.         this.val = val;
  37.         this.next = null;
  38.     }
  39. */
  40. /**
  41.  * @param {ListNode} head
  42.  *  @return {ListNode}
  43.  */
  44. function oddEvenLinkedList(head) {
  45.       let currentIndex=1;
  46.       let pointer=head, oddIndexValues=[],evenIndexValues=[],result=[],i=0;
  47.       while(pointer!=null){
  48.             if(currentIndex%2==1){
  49.                   oddIndexValues.push(pointer.val);
  50.             }else{
  51.                   evenIndexValues.push(pointer.val);
  52.             }
  53.             pointer=pointer.next;
  54.             currentIndex++;
  55.       }
  56.       result=oddIndexValues.concat(evenIndexValues);
  57.       pointer=head;
  58.       while(pointer!=null){
  59.             pointer.val=result[i];
  60.             i++;
  61.             pointer=pointer.next;
  62.       }
  63.       return head;
  64.  
  65.  
  66.  
  67.   }
  68.  
  69.  
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement