奇偶链表

暴力解法:摘取偶数的链表节点组成一个新的链表然后链到head的尾部,返回

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* 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 null;
let cur = head,
count = 1;
let head2 = null,
cur2 = null,
prev = null;
while (cur) {
// 偶数
if (count % 2 === 0) {
if (!head2) {
head2 = cur;
cur2 = head2;
prev.next = cur.next;
cur = cur.next;
cur2.next = null;
} else {
cur2.next = cur;
prev.next = cur.next;
cur = cur.next;
cur2.next.next = null;
cur2 = cur2.next;
}
} else {
prev = cur;
cur = cur.next;
}
count++;
}
prev.next = head2;
return head;
};

本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。