Java教程

25. Reverse Nodes in k-Group

本文主要是介绍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;
}
这篇关于25. Reverse Nodes in k-Group的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!