Skip to content

Latest commit

 

History

History
25 lines (21 loc) · 675 Bytes

算法-链表-双指针-删除倒数第n个.md

File metadata and controls

25 lines (21 loc) · 675 Bytes

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

给一个链表,删除倒数第n个节点

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode q = dummy, p = dummy;
        while(n-->-1){
            p = p.next;
        }
        while(p!=null){
            q = q.next;
            p = p.next;
        }
        q.next = q.next.next; // 优化:释放被删除节点
        return dummy.next;
    }
}

欢迎光临我的博客,发现更多技术资源~