Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given a singly linked list of integers, reverse every contiguous set of nodes that have only even values.
- 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 modified list
- Constraints
- 0 <= N <= 10^5
- -10^9 <= value <= 10^9
- Sample Input 1
- 8
- 1 2 3 3 4 6 8 5
- Sample Output 1
- 1 2 3 3 8 6 4 5
- Explanation 1
- There are two sublists of even elements, which [2] and [4->6->8]. The sublist [4->6->8] has been reversed and the single sublist [2] need not be reversed.
- Sample Input 2
- 6
- 1 3 2 5 4 6
- Sample Output 2
- 1 3 2 5 6 4
- Explanation 2
- There are two sublists of even elements which are [2] and [4 6]. The [4,6] sublist has been reversed and the single sublist [2] need not be reversed. Rest of the odd values remain constant.
- */
- /*
- class ListNode{
- constructor(val){
- this.val = val;
- this.next = null;
- }
- */
- /**
- * @param {ListNode} head
- * @return {ListNode}
- */
- function reverseEvenElements(head) {
- let pointer=head, arr=[], resultantArr=[],j=0;
- while(pointer!=null){
- let subarray=[];
- let currVal=pointer.val;
- if(currVal%2!=0){
- subarray.push(currVal);
- arr.push(subarray);
- pointer=pointer.next;
- }else{
- subarray.push(currVal);
- pointer=pointer.next;
- while(pointer!=null){
- let currVal=pointer.val;
- if(currVal%2==0){
- subarray.push(currVal);
- pointer=pointer.next;
- }else{
- arr.push(subarray);
- break;
- }
- }
- if(pointer==null){
- arr.push(subarray);
- }
- }
- }
- // console.log(arr);
- for(let i=0;i<arr.length;i++){
- if(arr[i].length>1){
- arr[i]=arr[i].reverse();
- // console.log("even subarray")
- // console.log(arr[i]);
- }
- resultantArr=resultantArr.concat(arr[i]);
- }
- // console.log(resultantArr);
- pointer=head;
- while(pointer!=null){
- pointer.val=resultantArr[j];
- j++;
- pointer=pointer.next;
- }
- return head;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement