美文网首页
328. Odd Even Linked List

328. Odd Even Linked List

作者: jluemmmm | 来源:发表于2021-11-30 20:58 被阅读0次

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

  • 时间复杂度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;
};

相关文章

网友评论

      本文标题:328. Odd Even Linked List

      本文链接:https://www.haomeiwen.com/subject/khfjxrtx.html