LeeCode-刷题日记-Day24
160. 相交链表
思路:双指针。让pA指针指向headA,pB指针指向headB。一起遍历,当pA指向null时让pA指向headB的头。当pB指向null时让pB指向headA的头。如果有共同节点则两个指针会相遇。
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
var getIntersectionNode = function(headA, headB) {
if(headA===null||headB===null){
return null;
}
let pA=headA,pB=headB;
while(pA!==pB){
pA=pA===null?headB:pA.next;
pB=pB===null?headA:pB.next;
}
return pA;
};
82. 删除排序链表中的重复元素 II
思路:首先创建一个空节点在head之前。如果下一个节点或者下下个节点的值相等,则保存当前节点的值,直到删除所有为此值的节点。
/**
* 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 deleteDuplicates = function(head) {
if(!head){
return head;
}
let dummy=new ListNode(0,head);
let cur=dummy;
while(cur.next&&cur.next.next){
if(cur.next.val===cur.next.next.val){
let x=cur.next.val;
while(cur.next&&cur.next.val === x){
cur.next=cur.next.next;
}
}else{
cur=cur.next;
}
}
return dummy.next;
};
- 本文链接:https://archer-lan.github.io/2023/11/20/LeeCode-%E5%88%B7%E9%A2%98%E6%97%A5%E8%AE%B0-Day24/
- 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。