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