每天刷一道牛客题霸-第12天-删除链表的倒数第n个节点

题目

https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6?tpId=188&&tqId=36726&rp=1&ru=/ta/job-code-high-week&qru=/ta/job-code-high-week/question-ranking

import java.util.*;
/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */
public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        int count = 0;
        ListNode root = head;
        while(root!=null){
            count++;
            root = root.next;
        }
        int index = count - n + 1;
        root = head;
        if(index != 1){
            while(root != null&& index<=count){
                index--;
                if(index == 1){
                    root.next = root.next.next;
                    break;
                }
                root = root.next;
            }
            return head;
        }else{
            return head.next;
        }
    }
}
#笔试题目##牛客题霸#
全部评论

相关推荐

头像 会员标识
05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
找工作时遇到的神仙HR
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务