19删除链表倒数第几个字母

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function(head, n) {
    let temp2 = head
    let length = 0
    while(temp2){
        length++
        temp2 = temp2.next
    }
    if(length == n){
        head = head.next
        return head
    }else{
        //链表顺序注意注意
        let myhead = head
        let myhead2 = head.next
        while(myhead2){
            let temp = myhead2
            let nowlength = 0
            while(temp){
                nowlength++
                temp = temp.next
            }
            if(nowlength == n){
                //说明是要的位置
                myhead.next = myhead2.next
                break
            }
            myhead = myhead2
            myhead2 = myhead2.next
        }
        return head
        
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41199852/article/details/106203655