题解 | #删除链表的倒数第n个节点#

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

https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        ListNode pre=head;
        ListNode after=head;
        for(int i=0;i<n;i++){
            after=after.next;
        }
        while(after!=null){
            after=after.next;
            if(after==null){
                //表示要删除了
                pre.next=pre.next.next;
                return head;
            }
            pre=pre.next;
        }
        
        //否则删除头结点
        return head.next;
    }
}
全部评论

相关推荐

头像
05-22 20:17
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务