题解 | #删除链表的倒数第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
        if (head == null) return null;
        ListNode preHead = new ListNode(0);
        ListNode preHead2 = preHead;
        preHead.next = head;
        ListNode index = head;
        int len = 0;
        while (index != null) {
            index = index.next;
            len++;
        }
        if (n > len) return null;
        int length = len - n;
        while (length != 0) {
            preHead = preHead.next;
            head = head.next;
            length--;
        }

        preHead.next = head.next;


        return preHead2.next;
    }
}

全部评论

相关推荐

笑死 不是哥们离校了我真要睡街了 加上还有几w的贷款 不接受我准备去当三和大神
梦想是成为七海千秋:没事,hr这下就有底气了,下次遇到一个不接受的就说,你看,人家这学历都接受了,你凭什么不接受
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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