美文网首页
Remove Nth Node From End of List

Remove Nth Node From End of List

作者: 瞬铭 | 来源:发表于2019-08-20 14:52 被阅读0次

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

      本文链接:https://www.haomeiwen.com/subject/zjdpsctx.html