将堆栈推到另一个堆栈上 [英] Push a stack onto another stack

查看:47
本文介绍了将堆栈推到另一个堆栈上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,有没有一种方法可以将一个堆栈推到另一个堆栈上而不迭代堆栈元素?如果没有,我应该使用更好的数据结构吗?在Java中,您可以执行以下操作:

In C#, is there a way to push one Stack onto another Stack without iterating through the stack elements? If not, is there a better data structure I should be using? In Java you can do:

stack1.addAll(stack2)

我希望找到C#类似物...

I was hoping to find the C# analogue...

推荐答案

0.安全解决方案-扩展方法

public static class Util {
        public static void AddAll<T>(this Stack<T> stack1, Stack<T> stack2) {
            T[] arr = new T[stack2.Count];
            stack2.CopyTo(arr, 0);

            for (int i = arr.Length - 1; i >= 0; i--) {
                stack1.Push(arr[i]);
            }
        }
    }

最好是创建一个扩展方法.请注意,我将第一个堆栈放在另一个堆栈的顶部",可以说是从arr.Length-1到0循环.因此,此代码:

Probably the best is to create an extension method. Note that I am putting the first stack "on top" of the other stack so to speak by looping from arr.Length-1 to 0. So this code:

  Stack<int> x = new Stack<int>();
  x.Push(1);
  x.Push(2);

  Stack<int> y = new Stack<int>();
  y.Push(3);
  y.Push(4);          

  x.AddAll(y);

将导致x为:4,3,2,1.如果您按1,2,3,4,这将是您期望的.当然,如果您要遍历第二个堆栈并实际弹出元素,然后将其推入第一个堆栈,则最终会得到1,2,4,3.同样,根据需要修改for循环.或者,您可以添加另一个参数来指定您想要的行为.我没有Java的方便,所以我不知道它们的作用.

Will result in x being: 4,3,2,1. Which is what you would expect if you push 1,2,3,4. Of course, if you were to loop through your second stack and actually pop elements and then push those to the first stack, you would end up with 1,2,4,3. Again, modify the for loop as you see fit. Or you could add another parameter to specify which behavior you would like. I don't have Java handy, so I don't know what they do.

话虽如此,您可以做到这一点,但是我不能保证它会继续工作.MS总是可以更改调用ToList时堆栈工作方式的默认行为.但是,它更短,并且在具有.NET 4.5的 my 机器上,其工作原理与上述扩展方法相同:

Having said that, you could do this, but I don't make any guarantees that it will continue to work. MS could always change the default behavior of how stack works when calling ToList. But, this is shorter, and on my machine with .NET 4.5 works the same as the extension method above:

1行Linq解决方案:

y.Reverse().ToList().ForEach(item => x.Push(item));

这篇关于将堆栈推到另一个堆栈上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆