链表操作 —— 19_删除链表倒数第N个结点

2. 19_删除链表倒数第N个结点
/**
 *给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
 * 利用两个指针 o(n)
 */
public class Solution {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode h = new ListNode(0);
        h.next = head;
        ListNode first = h;
        ListNode second = h;

        for (int i = 1; i <= n + 1; i++) {
            first = first.next;
        }

        while (first != null) {
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        return h.next;
    }
}
原文地址:https://www.cnblogs.com/s841844054/p/13736280.html