Topic describes

Method 1: double pointer, iterate once

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode slow = head, fast = head, pre = dummy;
        // Fast goes n distances first
        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }
        // All three Pointers move backwards
        while(fast ! =null) {
            fast = fast.next;
            slow = slow.next;
            pre = pre.next;
        }
        // If fast=null, the interval between fast and slow is n-1
        pre.next = slow.next;
        slow.next = null;
        returndummy.next; }}Copy the code

Method 2: Traverse twice, the first time to find the total length, the second time to locate the node to be deleted

class Solution {
    public ListNode deleteNode(ListNode head, int val) {
    ListNode dummy = new ListNode(0);// In order to delete the first element, or special processing of the first node is ok
    dummy.next = head;
    ListNode cur = dummy;
    while(cur ! =null) {
        if (cur.next.val == val) {
            cur.next = cur.next.next;
            break;
        } else{ cur = cur.next; }}returndummy.next; }}Copy the code

When dealing with removing a head node, there are two approaches

  1. Use dummyNode, dummy.next = dummy.next-next

  2. Special judgment, go straight back to head.next