【问题标题】:Stack count not working properly堆栈计数无法正常工作
【发布时间】:2013-10-12 15:24:36
【问题描述】:

为什么我的代码没有按预期工作? 尝试检查 stack.Count>0 是否工作不正常

toShort("../../../z") 正在返回“../z”,但它应该返回“../../../z” 更新:

static String toShort(String path)
    {
        String[] elements = path.Split('/');
        String result = "";
        Stack<String> stack = new Stack<String>();
        for (int i = 0; i < elements.Length; i++)
        {
            if (stack.Count>0&&elements[i].Equals(".."))
                stack.Pop();
            else
                stack.Push(elements[i]);
        }
        List<String>list = new List<String>();

        foreach (String str in stack)
            list.Add(str); 
        list.Reverse();
        int n = list.Count;
        for (int i = 0; i < n; i++)
            if (i != n - 1)
                result += list[i] + "/";
            else
                result += list[i];

        return result;
    }

【问题讨论】:

  • 它有什么作用?你期待它做什么?
  • 你想用顶级条件做什么?
  • 如果您告诉我们您期望它做什么以及它实际在做什么,那么回答您的问题会更容易。还有elements 数据类型是什么以及其中的内容。
  • 请比“无法正常工作”更具体。
  • "../z" 是我期望它返回的。为什么你认为它应该是“../../../z”?

标签: c# stack


【解决方案1】:

您的程序正在按照您的要求执行。堆栈工作正常。第二个.. 导致第一个.. 被删除。如果您在调试器中单步执行该程序,您会注意到这一点。

【讨论】:

    猜你喜欢
    • 2014-07-05
    • 2023-03-13
    • 2021-12-26
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2021-08-21
    • 2013-01-30
    相关资源
    最近更新 更多