阿基用快慢指针带你刷遍leetcode的链表题——删除链表节点题

剑指offer18.删除链表的节点

class Solution {
    public ListNode deleteNode(ListNode head, int val) {
        if(head.val == val){
            return head.next;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while(fast.val != val && fast!=null){
            slow = fast;
            fast = fast.next;   
        }
        if(fast !=null){
            slow.next = fast.next;
        }
        return head;
    }
}

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

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
       ListNode pre = new ListNode(0);
       pre.next = head;
       ListNode start = pre, end = pre;
       while(n != 0){
           start = start.next;
           n--;
       }
       while(start.next != null){
           start = start.next;
           end = end.next;
       }
       end.next = start;
       return pre.next;
    }
}

class Solution {
    public ListNode removeNthFromEnd(ListNode head,int n){
        ListNode pre = new ListNode(0) ;
        pre.next = head;
        ListNode fast = pre ,slow = pre;
        while(n>0){
            fast = fast.next;
            if(fast == null){
                return null;
            }
            n--;
        }
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = slow.next.next;
        return pre.next;
    }
}
有事评论区留言,也欢迎一起学习的伙伴
原文地址:https://www.cnblogs.com/wt9866/p/13859646.html