328. Odd Even Linked List
2021-11-30 本文已影响0人
jluemmmm
奇偶链表。给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。
- 时间复杂度O(n),空间复杂度O(1)
- Runtime: 92 ms, faster than 44.75%
- Memory Usage: 41.2 MB, less than 40.94%
/**
* 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) {
if (!head) return head;
let odd = head;
let even = head.next;
let tmp = even;
while (odd.next && even.next) {
odd.next = even.next;
odd = odd.next;
even.next = odd.next;
even = even.next;
}
odd.next = tmp;
return head;
};