算法练习day1--链表

60 阅读1分钟

1.定义链表:

class ListNode{
    val;
    next = null;
    constructor(val){
        this.val = val;
        this.next = null;
    }
}

2.移除链表元素

    function removeListNode(head ,val){
        let ret = new ListNode(0,head);
        let cur = ret;
        while(cur.next){
            if(cur.next.val === val){
                cur.next = cue.next.next;
                continue;
            }
            cur = cur.next
        }
        return ret.next
    }

3.翻转链表

    function reverseList(head){
        if(!head || !head.next) return head;
        let cur = head ,temp = pre = null;
        while(cur){
            temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }

4.两两交换表中的节点

    function swapPairs(head){
        let ret = head;
        let cur = ret
        while(cur.next && cur.next.next){
            let temp = cur.next.next,pre = cur.next;
            pre.next = temp.next;
            temp.next = pre;
            cur.next = temp;
            cur = pre;
        
        }
        return ret.next
    }

5.删除链表的倒数第N个节点

function removeNthFromEnd(head,n){
    let ret = new ListNode(0, head)
    let slow = fast = ret
    while(n--) fast = fast.next
    while(fast && fast !== slow){
        fast = fast.next
        slow = slow.next
    }
    slow.next = slow.next.next
    return ret.next
}

6.链表相交

function getLen(head){
    let cur = head,count = 0;
    while(cur){
        cur = cur.next ;
        count++;
    }
    return count
}
function getIntersectionNode(headA , headB){
    let curA = headA , curB = headB;
    let lenA = getLen(headA),lenB = getLen(headB);
    if(lenA < lenB){
        [curA , curB] = [curB , curA];
        [lenA , lenB] = [lenB , lenA];
    }
    let i = lenA - lenB;
    while(i-- > 0) curA = curA.next;
    while(curA && curA !== curB){
        curA = curA.next;
        curB = curB.next;
    }
    return curA
}

7.环形链表

    if(!head || !head.next){
        return null
    }
    let slow = head.next,fast = head.next.next;
    while(fast && fast.next && fast !== slow){
        fast = fast.next.next;
        slow = slow.next;
    }
    if(!fast && !fast.next.next){
        return null;
    }
    slow = head;
    while(fast !== slow){
        fast = fast.next;
        slow = slow.next;
    }
    return slow;
}