[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 };
原文地址:https://www.cnblogs.com/Liok3187/p/5181194.html