This is the 16th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge

preface

List operation for front-end developer’s still feeling strange, also don’t contact list in daily work related operations, this problem can be very good to let you have a know about linked list, this problem is a single table topic, we should first know the singly linked lists only a found a once upon a time, rather than from a found before a, Next =n1.next. Next. Next =n1.next

Topic describes

Give you a linked list, remove the NTH node from the reciprocal of the list, and return the head node of the list.

Advanced: Can you try using a scan implementation?

Example 1:

Enter: head = [1,2,3,4,5], n = 2

Output:,2,3,5 [1]

Example 2:

Enter head = [1], n = 1

Output: []

Example 3:

Enter head = [1,2], n = 1

Output: [1]

Their thinking

  • The first thing to know is that next of the last node in the list is null
  • First, we can find out the length of the input list by using the for loop. Then we can find out where the node to delete is by counting -n+1. If count is 5 and n is 2, then the node to be deleted is node 4, i.e. N1.next. Next.
  • First, define two Pointers, N1 and n2, pointing to dummy, and move n2 n times, then move n1 and n2 at the same time, until n2.next is null and stops. Then N1.next = N1.next. Next will get the deleted list
  • The above method is that n2 moves n times first, so we can make it move n plus one, and then move n1 and n2 together, and we know that n2 is null. The following operation is the same. The diagram and code are as follows

A graph of n2 moving n times: N 2 moves n+1 times:

The code is as follows:

/ * * *@param {ListNode} head
 * @param {number} n
 * @return {ListNode}* /
var removeNthFromEnd = function(head, n) {
    let dummy = new ListNode() Dummy is a linked list that has only one node and n = 1
    dummy.next = head

    let n1= dummy
    let n2= dummy

    for(let i=0; i<n; i++){For n+1 moves, I <=n. For n+1 moves, I <=n. ==null
        n2=n2.next
    }

    while(n2.next! = =null){
        n1= n1.next
        n2= n2.next
    }

    n1.next = n1.next.next
    return dummy.next
};
Copy the code

The running result of LeetCode is as follows:

conclusion

The linked list is an amazing data structure. It’s interesting. We will update a few more linked list questions later