logo CodeStepByStep logo

CollectionMystery8

Language/Type: C# collections Stack Queue

Write the output produced by the following method when passed each of the following stacks: Note that a stack prints in {bottom ... top} order.

public static void CollectionMystery8(Stack<int> stack)
{
    Queue<int> queue = new Queue<int>();
    SortedSet<int> set = new SortedSet<int>();
    while (stack.Count != 0)
    {
        if (stack.Peek() % 2 == 0)
        {
            queue.Enqueue(stack.Pop());
        }
        else
        {
            set.Push(stack.Pop());
        }
    }
    foreach (int n in set)
    {
        stack.Push(n);
    }
    while (queue.Count != 0)
    {
        stack.Push(queue.Dequeue());
    }
    Console.WriteLine(stack);
}
{1, 2, 3, 4, 5}
{3, 2, 7, 3, 3, 4, 1, 1, 4}
{9, 7, 14, 7, 22, 7, 3, 14}
{8, 5, 1, 2, 1, 1, 2, 1, 4, 5}

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.