c# - 将列表的最后一个成员放在列表的开头
问题描述
我正在用 C# 做一些练习,我的任务是在控制台中输入任何数字的列表,函数应该将列表的最后一个成员放在第一位,并将所有其他成员移到右边。例如,您可以在控制台中输入“1234”,结果应该是“4123”。我尝试了不同的方法,主要是遍历列表,但不知何故,我总是失去列表中的一个成员,并且我在新列表中有重复项。
挣扎了一两个小时后,我决定走更简单的路,我想出了以下代码:
var list = new List<char>(); //this is list that is populated from console
var repositionedList = list; //this is list i am editing
char[] tempArray = new char[repositionedList.Count - 1];
for (var i = 0; i < repositionedList.Count - 1; i++)
{
tempArray[i] = repositionedList[i];
}
repositionedList[0] = repositionedList[repositionedList.Count - 1];
for (var i = 1; i < repositionedList.Count; i++)
{
repositionedList[i] = tempArray[i - 1];
}
由于我没有任何编码经验,我想知道这样的做法是否不可接受。例如,我正在创建新数组,这很可能是不必要的,而且可能代价高昂,因此有更好的方法来完成结果。
解决方案
C# 中的List有一些帮助方法,使这变得更容易:
var list = new List<char>(); //this is list that is populated from console
var lastElement = list[list.Count - 1]; // Remember what the last element is
list.RemoveAt(list.Count - 1); // Remove the last element
list.Insert(0, lastElement); // Insert the element again, but at the first index
如果允许您使用 C# 列表,这可能是最简单的解决方案。
推荐阅读
- java - 继承中的方法调用有问题
- php - WooCommerce 在快速编辑时保存自定义产品字段
- bash - 计算机启动后 Anacrontab 未运行计划的 bash 脚本
- java - 为什么 return 不尊重 finally 块中变量的值?
- python-3.x - 如何计算分段线性斜率
- python - 抑制 GtkButton:image-spacing 的 Python matplotlib 弃用警告
- javascript - `this` 绑定和 `this` 的调用点
- kubernetes - Kubernetes Ingress Controller 返回 503 Service Unavailable
- launch4j - 将参数传递给从launch4j生成的现有exe
- javascript - 如何使方法'charCodeAt'在for循环之后工作?