BM14 链表的奇偶重排
题目描述
思路分析
新建两个头节点,再创建一个索引,遍历head,将奇号位节点挂在node1下,偶号位节点挂在node2下,
之后将节点连接在一起
参考代码
const oddEvenList = function (head) {
// 判断为空
if (head === null) return head
let node1 = new ListNode(-1), node2 = new ListNode(-1)
let p1 = node1, p2 = node2
// count记录奇偶位
let count = 1
while (head) {
if (count++ % 2 === 0) {
p1.next = head
p1 = p1.next
}
else {
p2.next = head
p2 = p2.next
}
head = head.next
}
// 将偶号位链表末尾置空
p1.next = null
p2.next = node1.next
console.log(node2.next)
return node2.next
}