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 };
  • 相关阅读:
    ES6 Promise用法讲解
    NPM使用介绍
    Docker学习系列(二):Docker三十分钟快速入门(上)
    Spring Cloud学习(一)
    胖ap和瘦ap的区别
    论网络知识的重要性
    2018 发发发发
    sikuli--前端自动化操作的神器
    更改MySQL数据库的编码为utf8mb4
    数据库mysql的常规操作
  • 原文地址:https://www.cnblogs.com/Liok3187/p/5181194.html
Copyright © 2011-2022 走看看