328. Odd Even Linked List

2021-11-30  本文已影响0人  jluemmmm

奇偶链表。给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。

/**
 * 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;
};
上一篇下一篇

猜你喜欢

热点阅读