zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Odd Even Linked List

    Odd Even Linked List

    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:
    Given 1->2->3->4->5->NULL,
    return 1->3->5->2->4->NULL.

    Note:
    The relative order inside both the even and odd groups should remain as it was in the input. 
    The first node is considered odd, the second node even and so on ...

    https://leetcode.com/problems/odd-even-linked-list/


    要求按照下标的奇偶顺序重排链表。

    遍历,开四个指针,两个(oddHead, evenHead)分别指向奇数链表头和偶数链表头;

    另两个(p, q)指向当前处理的奇数和偶数链表元素。

    最后把奇数和偶数链表连起来就好了。

     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     if(head === null || head.next === null) return head;
    14     var oddHead = new ListNode(-1), evenHead = new ListNode(-1);
    15     var p = oddHead, q = evenHead, isOdd = true;
    16     while(head !== null){
    17         if(isOdd){
    18             p.next = head;
    19             p = p.next;
    20             isOdd = false;
    21         }else{
    22             q.next = head;
    23             q = q.next;
    24             isOdd = true;
    25         }
    26         head = head.next;
    27     }
    28     q.next = null;
    29     p.next = evenHead.next;
    30     return oddHead.next;
    31 };
  • 相关阅读:
    intellij idea cpu占用率太大太满 运行速度太慢解决方案
    IntelliJ IDEA详细配置和使用(Java版)
    Bzoj2882 工艺
    SPOJ
    Bzoj2599 [IOI2011]Race
    Codeforces Round #398 (Div. 2) A-E
    Bzoj3653 谈笑风生
    Bzoj3652 大新闻
    URAL1960 Palindromes and Super Abilities
    Bzoj3676 [Apio2014]回文串
  • 原文地址:https://www.cnblogs.com/Liok3187/p/5181194.html
Copyright © 2011-2022 走看看