判断链表是否有环
js
// 标记法
function isCycle(list) {
while (list) {
if (list.sign) return true;
list.sign = true;
list = list.next;
}
return false;
}
// 通过系列化操作 无法序列化循环对象 function 等
function isCycle(list) {
try {
JSON.parse(JSON.stringify(list));
return false;
} catch {
return true;
}
}
// 快慢双指针
function isCycle(list) {
if (!head || !head.next) {
return false;
}
let slow = head.next,
fast = head.next.next;
while (slow !== fast) {
if (fast === null || fast.next === null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
合并两个有序链表
js
// 递归方法
function mergeList(l1, l2) {
if (!l1) return l2;
if (!l2) return l1;
if (l1.val <= l2.val) {
l1.next = mergeList(l1.next, l2);
return l1;
} else {
l2.next = mergeList(l1, l2.next);
return l2;
}
}
// 迭代
function mergeList(l1, l2) {
let list = new NodeList();
const prev = list; // 存取头结点
while (l1 && l2) {
if (l1.val <= l2.val) {
list.next = l1.next;
l1 = l1.next;
} else {
list.next = l2.next;
l2 = l2.next;
}
list = list.next;
}
list.next = l1 ? l1 : l2;
return prev.next;
}
反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
js
var reverseList = function (head) {
let prev = null,
list = head;
while (list) {
const tem = list.next;
list.next = prev;
prev = list;
list = tem;
}
return prev;
};
两数相加
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。 请你将两个数相加,并以相同形式返回一个表示和的链表。
js
var addTwoNumbers = function (l1, l2) {
let head = new ListNode(0);
let list = head;
let carry = 0;
while (l1 || l2 || carry) {
const sum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + carry;
carry = Math.floor(sum / 10);
list.next = new ListNode(sum % 10);
list = list.next;
l1 = l1 ? l1.next : null;
l2 = l2 ? l2.next : null;
}
return head.next;
}