当前位置:网站首页>NC53 删除链表的倒数第n个节点

NC53 删除链表的倒数第n个节点

2022-08-09 13:02:00 syc596

NC53 删除链表的倒数第n个节点

删除链表的倒数第n个节点_牛客题霸_牛客网 (nowcoder.com)


//11
//快慢指针
import java.util.*;
public class Solution {
    public ListNode removeNthFromEnd (ListNode head, int n) {
        ListNode slow=head;
        ListNode fast=head;
        for(int i=0;i<n;i++){
            fast=fast.next;
        }
        //要删除的节点是头节点
        if(fast==null){
            return head.next;
        }
        while(fast!=null&&fast.next!=null){
            slow=slow.next;
            fast=fast.next;
        }
        slow.next=slow.next.next;
        return head;
    }
}


// //长度统计
// import java.util.*;
// public class Solution {
//     public ListNode removeNthFromEnd (ListNode head, int n) {
//         ListNode cur=head;
//         int len=0;
//         while(cur!=null){
//             len++;
//             cur=cur.next;
//         }
//         if(len-n==0){
//             return head.next;
//         }
//         cur=head;
//         for(int i=0;i<len-n-1;i++){
//             cur=cur.next;
//         }
//         cur.next=cur.next.next;
//         return head;
//     }
// }

原网站

版权声明
本文为[syc596]所创,转载请带上原文链接,感谢
https://blog.csdn.net/A240428037/article/details/126189445