我有一个由N个整数组成的链表,我将其插入和删除。我需要做的另一项操作是将链表中的一堆元素增加相同的值。我尝试了以下操作,但由于.Take
上的LinkedList<int>
产生了一个只读的IEnumerable<int>
,它可能无法工作,而该static double superStackOptimized(string[] operations)
{
var watch = Stopwatch.StartNew();
Stopwatch.StartNew();
var superStack = new LinkedList<int>();
foreach (var operation in operations)
{
var operationParts = operation.Split(' ');
switch (operationParts[0].ToLower())
{
case "push":
superStack.AddLast(int.Parse(operationParts[1]));
break;
case "pop":
superStack.RemoveLast();
break;
case "inc":
var numOfValuesToInc = int.Parse(operationParts[1]);
var valueToIncBy = int.Parse(operationParts[2]);
var count = Math.Min(numOfValuesToInc
, superStack.Count);
Parallel.ForEach(superStack.Take(count)
, value => value += valueToIncBy); //did not work
superStack.Take(count).ToList().ForEach(val =>
{
val += valueToIncBy;
}); //did not work
break;
}
Console.WriteLine(superStack.Count > 0 ? $"{superStack.Last.Value}" : "EMPTY");
}
watch.Stop();
return watch.Elapsed.TotalMilliseconds;
}
在更新时对原始列表无效。还有其他方法可以实现这一目标。遍历列表和更新每个节点的常规方法在时间约束下无法通过测试。
private void ExecuteDeActivateCommand()
{
SetInactiveFlag(true);
GetProgramsSynchronously(SelectedRow.ID); //this call was what was causing me problems
}
答案 0 :(得分:1)
在链接列表项上调用.ToList()
时,您正在创建一个单独的列表,然后递增这些值,但不影响原始值。
要增加链接列表中的值,您只需使用var node = superstack.First
获取对头节点的引用,然后就可以增加该值并将其设置为{将引用移至下一个节点node.Next
循环中的{1}}:
for