25. Reverse Nodes in k-Group

SLinkedList<int> slist = new SLinkedList<int>();
slist.AppendRange(new[] { 1, 2, 3, 4, 5 });
Console.WriteLine("Input: " + slist.Print());
Console.WriteLine("k = 2");
var rslt = slist.ReverseKGroup(2);
Console.WriteLine("Output:" + rslt.Print());
Console.WriteLine("k = 3");
rslt = slist.ReverseKGroup(3);
Console.WriteLine("Output:" + rslt.Print());

/// <summary>
/// k 个相邻的元素,翻转链表,多余的继续保持
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="k"></param>
/// <returns></returns>
public static SLinkedList<T> ReverseKGroup<T>(this SLinkedList<T> source, int k) where T : IComparable<T>
{
    var tmp = new SLinkedList<T>(source);
    var node = ReverseKGroupImp(tmp.Head, k);
    return new SLinkedList<T>(node);
}
private static SLinkedListNode<T> ReverseKGroupImp<T>(SLinkedListNode<T> head, int k) where T : IComparable<T>
{
    var node = head;
    for (int i = 0; i < k; i++)
    {
        if (node == null)
        {
            return head;
        }
        node = node.Next;
    }
    var newHead = Reverse(head, node);
    head.Next = ReverseKGroupImp(node, k);
    return newHead;
}

private static SLinkedListNode<T> Reverse<T>(SLinkedListNode<T> first, SLinkedListNode<T> last) where T : IComparable<T>
{
    var prev = last;
    while (first != last)
    {
        var tmp = first.Next;
        first.Next = prev;
        prev = first;
        first = tmp;
    }
    return prev;
}
posted @ 2021-11-04 18:52  wesson2019  阅读(27)  评论(0编辑  收藏  举报