varhasCycle=function(head){let slow = head,fast = head
while(fast && fast.next){
slow = slow.next
fast = fast.next.next
if(slow === fast)returntrue}returnfalse};
倒数第k个节点删除
varremoveNthFromEnd=function(head, n){let headNode =newListNode(0,head)let p = headNode
let q = headNode
while(n--){
q = q.next
}while(q.next){
p = p.next
q = q.next
}
p.next = p.next.next
return headNode.next
};
两两交换链表中的节点
varswapPairs=function(head){let head1 =newListNode(0,head)let tmp = head1
while(tmp.next !==null&& tmp.next.next !==null){let p = tmp.next
let q = tmp.next.next
tmp.next = q
p.next = q.next
q.next = p
tmp = p
}return head1.next
};
k个一组翻转链表
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/varreverseKGroup=function(head, k){// 标兵let dummy =newListNode()
dummy.next = head
let[start, end]=[dummy, dummy.next]let count =0while(end){
count++if(count % k ===0){
start =reverseList(start, end.next)
end = start.next
}else{
end = end.next
}}return dummy.next
// 翻转stat -> end的链表functionreverseList(start, end){let[pre, cur]=[start, start.next]const first = cur
while(cur !== end){let next = cur.next
cur.next = pre
pre = cur
cur = next
}
start.next = pre
first.next = cur
return first
}};
相交链表
vargetIntersectionNode=function(headA, headB){if(headA ===null|| headB ===null){returnnull;}let pA = headA, pB = headB;while(pA !== pB){
pA = pA ===null? headB : pA.next;
pB = pB ===null? headA : pB.next;}return pA;};
回文链表
varisPalindrome=function(head){let slow = fast = head;let pre =null;while(fast && fast.next){
fast = fast.next.next;[slow.next, slow, pre]=[pre, slow.next, slow]//在前半个循环中找到中间,并且慢指针顺手将所过地区翻转, }// 出来while,fast或者fast.next已经null了,且前半段已经反转,下面 slow pre 开始配合 if(fast) slow = slow.next;//注意奇数个的话,slow需再单独往后走一个(通过打印pre slow fast 可看出来~)while(slow){if(slow.val !== pre.val)returnfalse;
slow = slow.next;
pre = pre.next;}returntrue;};
合并两个有序链表
varmergeTwoLists=function(l1, l2){let p = l1,q = l2
let head =newListNode(0)let cur = head
while(p !=null&& q !=null){if(p.val < q.val){
cur.next = p
p = p.next
}else{
cur.next = q
q = q.next
}
cur = cur.next
}while(p !=null){
cur.next = p
p = p.next
cur = cur.next
}while(q !=null){
cur.next = q
q = q.next
cur = cur.next
}return head.next
};
删除排序链表的重复元素
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*//**
* @param {ListNode} head
* @return {ListNode}
*/vardeleteDuplicates=function(head){var cur = head;while(cur && cur.next){if(cur.val == cur.next.val){
cur.next = cur.next.next;}else{
cur = cur.next;}}return head;};