Naive Approch for solving this Question
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var oddEvenList = function(head) {
let odd = [];
let even = [];
let current = head;
let count = 0;
while (current !== null) {
if (count % 2 === 0) {
even.push(current.val);
} else {
odd.push(current.val);
}
count++;
current = current.next;
}
const newArray = even.concat(odd);
head = null;
const insertAtLast = (data) => {
if (head === null) {
head = new ListNode(data);
} else {
let current = head;
while (current.next) {
current = current.next;
}
current.next = new ListNode(data);
}
};
for (let i = 0; i < newArray.length; i++) {
insertAtLast(newArray[i]);
}
return head;
};
Top comments (0)