力扣练习之删除链表的倒数第N个节点

我爱海鲸 2022-08-31 17:47:23 暂无标签

简介初级算法、链表

原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn2925/

解法一:

/**
 * 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) {
        ListNode pre = head;
        // 要删除节点的上一个节点
        int last = length(head) -n;
        if (last == 0) {
            return head.next;
        }
        for (int i = 0 ; i < last-1 ; i++) {
            pre = pre.next;
        }
        pre.next = pre.next.next;
        return head;
    }


    private int length(ListNode head) {
        int result = 0;
        while (head != null) {
            head = head.next;
            result ++;
        }
        return result;
    }
}

思路:

解法二:

/**
 * 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) {
        ListNode fast = head;
        ListNode slow = head;
        for (int i = 0 ; i < n; i++) {
            fast = fast.next;
        }
        if (fast == null) {
            return head.next;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }

}

思路:

定义两个快慢指针,快指针先走n步,走完后,如果快指针指向null,则表示删除的是头指针,直接返回头指针的下一个节点,如不等于null,在遍历快指针,同时也遍历慢指针,当快指针的下一个节点等于null时,停止遍历,那么此时慢指针的指向的位置就是需要删除节点的前一个节点,这是只要将慢指针的下一个节点指针指向慢指针的下一个的下一个指针即可。

你好:我的2025