LeetCode143 重排链表
题目
解题
解题一:线性表
// javascript
var reorderList = function(head) {
if (head === null) return;
const vec = new Array();
let curr = head;
while (curr !== null) {
vec.push(curr);
curr = curr.next;
}
let i = 0; j = vec.length - 1;
while (i < j) {
vec[i].next = vec[j];
i++;
if (i === j) break;
vec[j].next = vec[i];
j--;
}
vec[i].next = null;
};
解题二:寻找链表中点 + 链表逆序 + 合并链表
// javascript
var reorderList = function(head) {
if (head === null) return;
// 寻找链表中点
const firstHalfTail = getMiddlenNode(head);
let secondHalfHead = firstHalfTail.next;
firstHalfTail.next = null;
// 链表逆序
secondHalfHead = reverseList(secondHalfHead);
// 合并链表
return mergeLists(head, secondHalfHead);
};
const getMiddlenNode = (head) => {
let fast = head, slow = head;
while (fast.next !== null && fast.next.next !== null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
};
const reverseList = (head) => {
let prev = null;
while (head !== null) {
const next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
};
const mergeLists = (l1, l2) => {
while (l1 !== null && l2 !== null) {
const nextl1 = l1.next;
const nextl2 = l2.next;
l1.next = l2;
l1 = nextl1;
l2.next = l1;
l2 = nextl2;
}
};