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.RotateRight(2);
Console.WriteLine(rslt.Print());

25. Reverse Nodes in k-Group

/// <summary>
/// 向右旋转链表 k 次
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="k"></param>
/// <returns></returns>
public static SLinkedList<T> RotateRight<T>(this SLinkedList<T> source, int k) where T : IComparable<T>
{
    if (source.Head == null || source.Head.Next == null || k == 0)
    {
        return source;
    }
    var len = source.Count;
    if (k % len == 0)
    {
        return source;
    }

    var tmp = new SLinkedList<T>(source);
    var head = tmp.Head;
    var tmp2 = new SLinkedList<T>(head);
    var newHead = tmp2.Head;
    var cur = newHead;
    while (cur.Next != null)
    {
        cur = cur.Next;
    }
    // 连接
    cur.Next = head;
    cur = newHead;
    for (int i = len - k % len; i > 0; i--)
    {
        cur = cur.Next;
    }
    var res = new SLinkedList<T>();
    for (int i = 0; i < len; i++)
    {
        res.Append(cur.Data);
        cur = cur.Next;
    }
    return res;
}
上一篇:小程序picker地区级联选择的问题及解决方案


下一篇:LeetCode-107-二叉树的层序遍历 II