奇偶链表。题意是给一个链表,请按照node的奇偶性重新排列,奇数在前,偶数在后。注意不是按照node.val而是按照node number。例子,
没什么好解释的,看懂代码,思路也就看懂了。
时间O(n)
空间O(1)
1 /** 2 * Definition for singly-linked list. 3 * function ListNode(val) { 4 * this.val = val; 5 * this.next = null; 6 * } 7 */ 8 /** 9 * @param {ListNode} head 10 * @return {ListNode} 11 */ 12 var oddEvenList = function(head) { 13 // corner case 14 if (head === null || head.next === null) { 15 return head; 16 } 17 18 // normal case 19 let first = head; 20 let second = head.next; 21 let secondHead = second; 22 while (second !== null && second.next !== null) { 23 first.next = first.next.next; 24 second.next = second.next.next; 25 first = first.next; 26 second = second.next; 27 } 28 first.next = secondHead; 29 return head; 30 };