【算法】【线性表】【链表】Remove Nth Node From End of List 删除链表的倒数第N个节点

1  题目

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

Example 1:

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

Input: head = [1], n = 1
Output: []

Example 3:

Input: head = [1,2], n = 1
Output: [1]

Constraints:

  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

2  解答

这里有一个巧妙的点就是 倒数第n个节点:

比如有10个节点,删除倒数第2个,双指针法

第一个指针先遍历 2个,然后第二个指针还是从头开始遍历,当第一个指针遍历到尾部时,第二个指针的下一个节点就是要被删除的节点,第二个指针跟第一个指针相差2个节点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // 参数边界考虑
        if (head == null || n <= 0) {
            return head;
        }
        // 链表就一个元素 直接返回吧
        if (head.next == null) {
            return null;
        }
        // 双指针法
        // node先遍历 n个
        ListNode node = head;
        for (int i = 0; i < n - 1; i++) {
            node = node.next;
        }
        // 加个头节点
        // preNode 永远指向被删除节点的前一个节点
        // 这个要理解
        ListNode preNode = new ListNode(0);
        preNode.next = head;

        // 如果删除的是第一个节点 那么就不会进入while循环
        while (node.next != null) {
            node = node.next;
            preNode = preNode.next;
        }
        
        ListNode delNode = preNode.next;
        preNode.next = delNode.next;
        // 如果删除的是第一个节点,就返回 preNode.next 否则就返回head
        return delNode == head ? preNode.next : head;
    }
}

加油。

posted @ 2024-01-15 07:45  酷酷-  阅读(1)  评论(0编辑  收藏  举报