保留栈的一半元素 - 算法与数据结构面试分享(二十六)

昨天群里有同学在问这样一道题,大体的意思是说利用栈的常用操作将原栈中元素删除一半,可以构造辅助栈。我们看下原题哈。

Give the lines of code that delete the bottom half of a stack S1. For example, the code should achieve the following, use only the top(), Push(), Pop(), and emptyCheck(), operates and create additional stacks where necessary. 


大多数同学应该能读懂题的哈。这时候其实我们想到的就是构造一个辅助栈,按照如下步骤:

1. 构造辅助栈,设计数器count=0

2. While当S1不为空,我们出栈,count++,将元素压入辅助栈

3. 计算 half = count/2

4. while count > 0 我们将辅助栈出栈。并检查

4.1 if half > 0 , 我们出栈后什么也不做

4.2 else 我们出栈后要压入原栈

4.3 half --; count --

我们一起来实现以下代码哈:

     public static void CutBottomHalf(Stack<char> s)
        {
            if (s != null)
            {
                Stack<char> helpStack = new Stack<char>();
                int count = 0;

                while (s.Count > 0)
                {
                    count++;

                    char element = s.Pop();

                    helpStack.Push(element);
                }

                int half = count / 2;

                while (helpStack.Count > 0)
                {
                    char element = helpStack.Pop();

                    if (half < 1)
                    {
                        s.Push(element);
                    }

                    half--;
                }
            }
        }

看下测试结果:


这道题我们就聊到这哈。欢迎大家关注我的公众号,访问我的视频学习更多资源。

算法与数据结构

BAT、微软、Google 经典面试题

排序算法专题精讲

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值