当前位置:网站首页>【Hot100】19. Delete the penultimate node of the linked list

【Hot100】19. Delete the penultimate node of the linked list

2022-07-01 16:05:00 Wang Liuliu's it daily

19. Delete the last of the linked list N Nodes
Medium question

 Insert picture description here
Virtual header node + Double pointer
fast Move first n+1 Step , leading n Nodes , bring slow and fast Interval between n-1 Nodes .
interval n-1 Nodes lead n Nodes .

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */
class Solution {
    
    public ListNode removeNthFromEnd(ListNode head, int n) {
    
        // Virtual header node 
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode slow = dummy,fast = dummy;

        // send slow and fast interval n-1 Nodes 
        for(int i=0;i<=n;i++){
    
            fast = fast.next;
        }
        while(fast != null){
    
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = slow.next.next;
        return dummy.next;// Returns the entire list 

    }
}
原网站

版权声明
本文为[Wang Liuliu's it daily]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207011549208318.html