LeetCode 19 删除链表的倒数第N个节点

LeetCode 19 删除链表的倒数第N个节点

问题描述:
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

双指针

  • 两指针间刚好间隔N个节点

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:36.3 MB, 在所有 Java 提交中击败了98.82%的用户

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null) {
            return head;
        }
        
        ListNode p1 = head, p2 = head;
        int curr = 0;
        while(curr<n) {
            p2 = p2.next;
            curr++;
            if(p2==null) {
                //倒数第n个节点为头节点
                if(curr==n) {
                    return head.next;
                }
                //链表长度小于n
                else {
                    return head;
                }
            }
        }

        while(p2.next!=null) {
            p1 = p1.next;
            p2 = p2.next;
        }

        ListNode tmp = p1.next;
        p1.next = tmp.next;
        tmp.next = null;

        return head;
    }
}
posted @ 2020-10-18 10:33  CodeSPA  阅读(54)  评论(0编辑  收藏  举报