LeetCode 19. Remove Nth Node From End of List 删除链表中倒数第n个节点

题目

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

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

For 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.
Try to do this in one pass.

讲解

本题核心是找到需要删除的节点的前一个节点位置。我们可以引用一个preDelete的指针变量,使preDelete和head之间的距离为需要删除的节点的前一个节点和null的距离相同。

  1. 首先,移动head指针,让head和preDelete指针变量间相差N个节点。
  2. 接着在链表上同时移动head和preDelete直到head为null。
  3. 修改preDelete所在的节点的next指向删除节点的下一个节点。

视频教学

Java参考代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (n <= 0) {
            return head;
        }
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode preDelete = dummy;
        
        for (int i = 0; i < n; i++) {
            if (head == null) {
                return null;
            }
            head = head.next;
        }
        
        while (head != null) {
            preDelete = preDelete.next;
            head = head.next;
        }
        
        preDelete.next = preDelete.next.next;
        
        return dummy.next;
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注