链表操作 —— 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;
    }
}
posted @ 2020-09-26 19:19  SSunSShine  阅读(49)  评论(0编辑  收藏  举报