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

xiaoxiao2021-02-28  35

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

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 经典面试题

排序算法专题精讲

 

转载请注明原文地址: https://www.6miu.com/read-2621582.html

最新回复(0)