24. 两两交换链表中的节点
这题的核心思想其实就是下面这幅图,效仿着这幅图去设计,答案就很浅显易懂了。
具体代码如下:
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
const dummy = new ListNode(0,head);
let temp = dummy;
while(temp.next && temp.next.next){
let cur = temp.next;
let fast = temp.next.next;
cur.next = fast.next;
fast.next = cur;
temp.next = fast;
temp = cur;
}
return dummy.next;
};
先声明一个虚拟头节点,然后设计三个指针指向虚拟头节点,头节点和第二个节点,然后就水到渠成了~
19.删除链表的倒数第N个节点
原理很简单,先遍历一遍获得链表长度,然后根据倒数节点数反推正数节点数,之后删除就完事儿了:
var removeNthFromEnd = function(head, n) {
let cur = head;
let count = 0;
while(cur){
cur = cur.next;
count++;
}
let index = count - n;
if(index === 0){
const node = new ListNode(0,head);
cur = node;
cur.next = cur.next.next;
return cur.next;
}
cur = head;
while(index - 1){
cur = cur.next;
index--;
}
cur.next = cur.next.next;
return head;
};
面试题 02.07. 链表相交
链表若相交,意味着链表后面的部分总有相同,将两个链表从等长度开始往后遍历,直至相交或者不相交:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
let getSize = function(head){
let cur = head;
let size = 0;
while(cur){
cur = cur.next;
size++;
}
return size;
}
var getIntersectionNode = function(headA,headB) {
sizeA = getSize(headA);
sizeB = getSize(headB);
if(sizeA < sizeB){
[sizeA,sizeB] = [sizeB,sizeA];
[headA,headB] = [headB,headA];
}
let cur = headA;
let cur2 = headB;
while(sizeA - sizeB){
cur = cur.next;
sizeA--;
}
while(cur){
if(cur === cur2){
return cur;
}
cur = cur.next;
cur2 = cur2.next;
}
return null;
};
142.环形链表II
这个太麻烦了,上代码随想录看Carl哥的解析吧:
/**
* 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 === null || head.next === null) return null;
let slow = head.next;
let fast = head.next.next;
while(fast && fast.next && slow !== fast){
slow = slow.next;
fast = fast.next.next;
}
if(fast === null || fast.next === null){
return null;
}
let cur = slow;
slow = head;
while(cur !== slow){
cur = cur.next;
slow = slow.next;
}
return slow;
};