19. Remove Nth Node From End of List

删除链表中倒数第 n 个结点。

SLinkedList<int> slist = new SLinkedList<int>();
slist.AppendRange(new[] { 1, 2, 3, 4, 5 });
Console.WriteLine(slist.Head.Print());
Console.WriteLine("n = 2");
slist.RemoveNthFromEnd(2);
Console.WriteLine(slist.Head.Print());

/// <summary>
/// 删除链表中倒数第 n 个结点
/// </summary>
/// <param name="n">链表中倒数第 n 个结点</param>
/// <returns></returns>
public void RemoveNthFromEnd(int n)
{
    if (n > Count)
    {
        return;
    }
    // 设置快慢指针,间隔n个距离。同时移动,快指针到链尾时,慢指针即指向第n个结点
    var fast = Head;
    var slow = Head;
    for (int i = 0; i < n; i++)
    {
        fast = fast.Next;
    }
    // 若删除的是头结点
    if (fast == null)
    {
        Head = Head.Next;
        return;
    }
    while (fast.Next != null)
    {
        fast = fast.Next;
        slow = slow.Next;
    }
    slow.Next = slow.Next.Next;
}
posted @ 2021-11-02 17:27  wesson2019  阅读(26)  评论(0编辑  收藏  举报