24. 两两交换链表中的节点
题目链接:24. 两两交换链表中的节点
思路:使用虚拟头节点
刚开始没有画图,在temp.next = cur卡了好久,画图后,就很清晰了
题解:
/**
* 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 swapPairs = function(head) {
const node = new ListNode(0, head);
let temp = node;
while(temp.next && temp.next.next) {
let cur = temp.next.next;
let pre = temp.next;
pre.next = cur.next;
cur.next = pre;
temp.next = cur;
temp = pre;
}
return node.next;
};
19. 删除链表的倒数第 N 个结点
题目链接:19. 删除链表的倒数第 N 个结点
思路:虚拟头结点+双指针,fast指针先走n步,然后fast和slow指针一起走,直到fast指向链表末尾(fast.next为null)。删掉slow所指向的节点(slow.next = slow.next.next)
题解:
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
const node = new ListNode(0, head);
let fast = node;
let slow = node;
while(n--) {
fast = fast.next;
}
while(fast.next) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return node.next;
};
面试题 02.07. 链表相交
题目链接:面试题 02.07. 链表相交
思路:先求两个链表的长度,求出两个链表的长度差n,然后让长的链表走n步,然后长的链表和短的链表一起走,如果相等,则返回
题解:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
const getLen = (head) => {
let cur = head;
let size = 0;
while(cur) {
cur = cur.next;
size++;
}
return size;
}
var getIntersectionNode = function(headA, headB) {
let curA = headA;
let curB = headB;
let sizeA = getLen(headA);
let sizeB = getLen(headB);
if (sizeA < sizeB) {
[curA, curB] = [curB, curA];
[sizeA, sizeB] = [sizeB, sizeA];
}
let n = sizeA - sizeB;
while(n--) {
curA = curA.next;
};
while(curA ) {
if(curA === curB) {
return curA;
}
curA = curA.next;
curB = curB.next;
}
};
142. 环形链表 II
题目链接:142. 环形链表 II
思路:先确定是否为环,fast指针走两步,slow指针走一步,
如果两个指针相遇,则为环;
从相遇结点出发个指针走一步,从头节点出发个指针走一步,两个指针相遇的结点为环形入口
题解:
//**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var detectCycle = function(head) {
if(!head || !head.next) return null;
let slow =head.next, fast = head.next.next;
while(fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
if(fast == slow) {
slow = head;
while (fast !== slow) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
};