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());
/// <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;
}
标签:25,Group,cur,SLinkedList,source,var,new,Nodes,Next 来源: https://www.cnblogs.com/wesson2019-blog/p/15554680.html