Remove Nth Node From End of List

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

仅仅想记录一下两个case
[1,2] n=2的情况
[1] n=1的情况 怎么解决
用的是这段代码,翻译就是,当发现要删除的是第一个元素的时候,直接把res的next返回

     if(k3.next == null){
            res = res.next;
            return res;
        }

贴上代码

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode k1 = new ListNode(-1);
        ListNode k2 = new ListNode(-1);
        ListNode k3 = new ListNode(-1);
        ListNode res = new ListNode(-1);
        k3 = head;
        res = k3;
        while (n > 1) {
            k3 = k3.next;
            n--;
        }
        k2 = head;
        k1.next = k2;

        if(k3.next == null){
            res = res.next;
            return res;
        }
        while (k3.next != null) {
            k1 = k1.next;
            k2 = k2.next;
            k3 = k3.next;
        }
        //删除
        k1.next = k2.next;
        return res;
    }

你可能感兴趣的:(Remove Nth Node From End of List)