Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example 1:
Input: 1->2->3->4->5->NULLOutput: 1->3->5->2->4->NULL
Example 2:
Input: 2->1->3->5->6->4->7->NULLOutput: 2->3->6->7->1->5->4->NULL
Note:
cur nextInput: 1 -> 2 -> 3 -> 4 -> 5 -> NULLprev cur next1 -> 2 -> 3 -> 4 -> 5 -> NULL..prev cur next 遍历完成后, 如果此时是奇数位则将 cur 的指针指向偶数列表。1 -> 2 -> 3 -> 4 -> 5 -> NULLOutput: 1 -> 3 -> 5 -> 2 -> 4 -> NULL
/*** Definition for singly-linked list.* function ListNode(val) {* this.val = val;* this.next = null;* }*//*** @param {ListNode} head* @return {ListNode}*/var oddEvenList = function(head) {if (!head) return headconst list = new ListNode(0)list.next = headconst odd = list.nextconst even = odd.nextlet prev = nulllet cur = list.nextlet next = cur.nextlet count = 1while (next) {prev && (prev.next = next)prev = curcur = nextnext = cur.nextcount++}if (count % 2 === 1) {prev && (prev.next = null)cur.next = even} else {prev.next = even}return odd}