const removeNthFromEnd = function (head, n) {
// 哨兵
let preHead = new ListNode(0)
preHead.next = head
let slow = preHead;
let fast = preHead;
// 先走n步
while (n--) {
fast = fast.next
}
// 一起走
while (fast && fast.next) {
fast = fast.next
slow = slow.next
}
slow.next = slow.next.next
return preHead.next;
};
6、回文链表
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false
示例:
输入: head = [1,2,2,1]
输出: true
步骤:
解题的链表类型是单链表
思路:
借助数组,将链表丢进数组
设置前后指针,前后指针理应相同,若不同则不是回文
循环结束若没有返回false则是回文
边界条件:
前后指针不一致
循环结束
var isPalindrome = function (head) {
const res = []
while (head) {
res.push(head.val);
head = head.next
}
let pre = 0;
let last = res.length - 1;
while (pre < last) {
if (res[pre] !== res[last]) return false;
pre++;
last--;
}
return true
}
const addTwoNumbers = function (l1, l2) {
// 哨兵
let preHead = new ListNode(0)
let carry = 0;
let pre = preHead;
while (l1 || l2) {
let sum = 0;
if (l1) {
sum += l1.val
l1 = l1.next
}
if (l2) {
sum += l2.val
l2 = l2.next
}
sum += carry
carry = Math.floor(sum / 10)
pre.next = new ListNode(sum % 10)
pre = pre.next
}
if (carry > 0) {
pre.next = new ListNode(carry)
pre = pre.next
}
return preHead.next
}