【问题标题】:need assistance with pop and push operations在弹出和推送操作方面需要帮助
【发布时间】:2017-08-23 22:08:16
【问题描述】:

我正在准备微软考试,其中一道备考题如下:

您有一个包含整数值的堆栈。这些值按以下顺序压入堆栈:2、4、6、8。 执行以下操作序列:

流行音乐, 按3, 流行音乐, 按4, 推6, 按7, 流行音乐, 流行音乐, 流行音乐,

这些操作执行后顶部元素的值是多少?

A. 2

B. 3

C. 6

D. 7

正确答案:B

为什么 B 是正确答案?

【问题讨论】:

  • 同意答案; 不可能在这些操作之后,堆栈中仍然有 3 个(它立即被弹出)
  • 作为旁注,我曾经在基本上是现有考试问题转储的网站上进行培训。那里经常有明显的错误,可能问题没有正确复制到系统中。不要相信这些网站上的答案。尤其是在没有解释的情况下。我个人对大约一千个问题的经验是,至少有 10% 的所谓解决方案是错误的。
  • 书本上的问题,或多或少是官方的,也包含错误!
  • 这有点令人沮丧...我一直在使用这些准备问题

标签: stack


【解决方案1】:

堆栈是一种 LIFO(后进先出)结构。 “Pop”会删除你最后放的东西。

2 4 6 8
Pop
2 4 6
Push 3
2 4 6 3
Pop
2 4 6
Push 4
2 4 6 4
Push 6
2 4 6 4 6
Push 7
2 4 6 4 6 7
Pop
2 4 6 4 6
Pop
2 4 6 4
Pop
2 4 6

对我来说,6 在最后的堆栈的顶部(意味着将弹出的下一个元素),所以 C 是正确的答案

【讨论】:

  • 我也有同样的想法……似乎这个准备问题不正确。感谢您的澄清。
【解决方案2】:

也同意这个答案...用代码检查

namespace StackTest
{
    class Program
    {
        static void Main(string[] args)
        { 
            Stack st = new Stack(); 
            // Starting
            st.Push(2);
            st.Push(4);
            st.Push(6);
            st.Push(8);
            // Showing state 
            ShowStack(st,"Contenido inicial");
            //Pop, Push 3, Pop, Push 4, Push 6, Push 7, Pop, Pop, Pop,
            st.Pop();
            ShowStack(st, "Quitar uno");
            st.Push(3);
            ShowStack(st, "Agregado 3");
            st.Pop();
            ShowStack(st, "Quitar uno");
            st.Push(4);
            ShowStack(st, "Agregado 4");
            st.Push(6);
            ShowStack(st, "Agregado 6");
            st.Push(7);
            ShowStack(st, "Agregado 7");
            st.Pop();
            st.Pop();
            st.Pop();
            ShowStack(st, "Quitar tres");
            ShowStack(st,"Situacion Final");   
            Console.ReadKey();
            // 2, 4 , 6 , 8
        }
        private static void ShowStack(Stack st,string message)
        {
            Console.WriteLine(message);
            foreach (var item in st)
            {
                Console.WriteLine(item.ToString());
            }
            Console.WriteLine("-------------------");
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 2011-01-27
    • 2014-02-06
    • 2017-11-02
    相关资源
    最近更新 更多