首页 > 解决方案 > 将列表的最后一个成员放在列表的开头

问题描述

我正在用 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#

解决方案


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# 列表,这可能是最简单的解决方案。


推荐阅读