【问题标题】:How do I take each element off of a list and push it onto a stack?如何从列表中取出每个元素并将其推入堆栈?
【发布时间】:2020-06-30 16:56:15
【问题描述】:
string filePath = @"C:\Users\Me\Desktop\Palindromes\palindromes.txt";

List<string> lines = File.ReadAllLines(filePath).ToList();
var meStack = new Stack<string>();

for (int i = 0; i < lines.Count; i++)
{
    string pali;
    pali = lines.RemoveAt(i);
    meStack.Push(pali[i]);
}

基本上我需要Remove list 中的每个元素(在 txt 中有 40 行),然后 Push 每个 一个到 stack。 p>

【问题讨论】:

  • 你好,马文!你能考虑把代码 sn-p 格式化好一点吗?
  • 问题是您从头到尾迭代并删除项目。因此,第一次迭代您将删除索引 0。在下一次迭代中,新项目将位于位置 0,这将被跳过,因为 i 现在是 1。处理此类情况的一种方法是从后面开始并迭代开始。那么是否删除项目并不重要,因为它们总是有更高的索引。

标签: c# list stack push


【解决方案1】:

为什么还要列出List&lt;String&gt;ReadAllLines 回复 String[]。 Stack 将一个数组作为构造函数参数......那么,下面的代码会为您完成这项工作吗?

  string filePath = @"C:\Users\Me\Desktop\Palindromes\palindromes.txt";
  var meStack = new Stack<string>(File.ReadAllLines(filePath));

【讨论】:

【解决方案2】:

不要RemoveAt,而是Clear(如有必要)在最后列出lines

  for (int i = 0; i < lines.Count; ++i)
    meStack.Push(lines[i]);

  lines.Clear();

甚至(我们可以完全摆脱列表):

  string filePath = @"C:\Users\Me\Desktop\Palindromes\palindromes.txt";

  var meStack = new Stack<string>(); 

  foreach (var item in File.ReadLines(filePath))
    meStack.Push(item);

【讨论】:

    【解决方案3】:

    你可以把它简化成

    lines.ForEach(meStack.Push);
    lines.Clear();
    

    【讨论】:

    • @Fildor,抱歉忘记添加了,应该添加,谢谢
    • 没什么好遗憾的。我喜欢在我的答案中添加参考链接。有点养成了习惯。随意将其添加到您的答案中。我发现特别是新用户有时甚至不知道,这些文档是可用的。
    【解决方案4】:

    带有一些 cmets 的代码:

    string filePath = @"C:\Users\Me\Desktop\Palindromes\palindromes.txt";
    List<string> lines = File.ReadAllLines(filePath).ToList();
    var meStack = new Stack<string>();
    
    for (int i = 0; i < lines.Count; i++)
    {
       string pali;
       pali = lines.RemoveAt(i); // < this will return AND REMOVE the line from the list.
                                 // now, what was line i+1 is now line i, next iteration
                                 // will return and remove (the new) line i+1, though,
                                 // skipping one line.
       meStack.Push(pali[i]);    // here you push one char (the ith) of the string (the line you  
                                 // just removed) to the stack which _may_ cause an 
                                 // IndexOutOfBounds! (if "i" >= pali.Length )
    }
    

    现在,由于我不想重复其他(很好的)答案,这里有一个您可以实际使用 RemoveAt 的答案:

    while( lines.Count > 0 ) // RemoveAt will decrease Count with each iteration
    {
        meStack.Push(lines.RemoveAt(0)); // Push the whole line that is returned.
        // Mind there is hardcoded "0" -> we always remove and push the first
        // item of the list.
    }
    

    这不是最好的解决方案,只是另一种选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 2017-03-27
      • 1970-01-01
      相关资源
      最近更新 更多