LeetCode上删除链表末尾第N个节点算法——Remove Nth Node From End of List

1.题目

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.


2.中文翻译

给定链接列表,从列表末尾删除第n个节点并返回其头部。
例:
给出链表:1-> 2-> 3-> 4-> 5,n = 2。
从末尾删除第二个节点后,链表变为1-> 2-> 3-> 5。
注意:

给定n将始终有效。

3.解析

处理这种问题,我们首先考虑的是时间复杂度和空间复杂度的问题,利用有限的资源,有效的解决问题才是我们锻炼的目的。在这里,可以定义一个节点p和q,同时指向头结点,用一个变量k(k初始位0)跟进链表节点的位置,当k<0时,p不移动,否则移动,此外,保证q是一直移动的,这样,在q移到末尾时,p刚好移动到倒数第n个位置。这其实利用到了对称性原理,可以画图更好的理解。

4.算法代码:

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode p=head,q=head;
        int k=0;
        while (q!=null){
             if (q.next==null){
                 if (k+1==n) head=head.next;
                 else p.next=p.next.next;
            }
            if (k<n) k++;
            else p=p.next;
            q=q.next;
        }
        return head;
    }
}

5.提交结果

LeetCode上删除链表末尾第N个节点算法——Remove Nth Node From End of List