`
温柔一刀
  • 浏览: 865184 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

9.2. Working with Stacks and Queues

阅读更多

Stacks and queues are the first entities we have discussed that are not strictly built into Ruby. By this we mean that Ruby does not have Stack and Queue classes as it does Array and Hash classes (except for the Queue class in tHRead.rb, which we'll mention later).

And yet, in a way, they are built into Ruby after all. In fact, the Array class implements all the functionality we need to treat an array as a stack or a queue. We'll see this in detail shortly.

A stack is a last-in first-out (LIFO) data structure. The traditional everyday example is a stack of cafeteria trays on its spring-loaded platform; trays are added at the top and also taken away from the top.

A limited set of operations can be performed on a stack. These include push and pop (to add and remove items) at the very least; usually there is a way to test for an empty stack, and there may be a way to examine the top element without removing it. A stack implementation never provides a way to examine an item in the middle of the stack.

You might ask how an array can implement a stack since array elements may be accessed randomly, and stack elements may not. The answer is simple. A stack sits at a higher level of abstraction than an array; it is a stack only so long as you treat it as one. The moment you access an element illegally, it ceases to be a stack.

Of course, you can easily define a Stack class so that elements can only be accessed legally. We will show how this is done.

It is worth noting that many algorithms that use a stack also have elegant recursive solutions. The reason for this becomes clear with a moment's reflection. Function or method calls result in data being pushed onto the system stack, and these data are popped upon return. Thus a recursive algorithm simply trades an explicit user-defined stack for the implicit system-level stack. Which is better? That depends on how you value readability, efficiency, and other considerations.

A queue is a first-in first out (FIFO) data structure. It is analogous to a group of people standing in line at (for example) a movie theater. Newcomers go to the end of the line, while those who have waited the longest are the next served. In most areas of programming, queues are probably used less often than stacks.

Queues are useful in more real-time environments where entities are processed as they are presented to the system. They are useful in producer-consumer situations (especially where threads or multitasking are involved). A printer queue is a good example; print jobs are added to one end of the queue, and they "stand in line" until they are removed at the other end.

The two basic queue operations are usually called enqueue and dequeue in the literature. The corresponding instance methods in the Array class are called unpush and shift, respectively.

Note that unshift could serve as a companion for shift in implementing a stack, not a queue, because unshift adds to the same end from which shift removes. Various combinations of these methods could implement stacks and queues, but we will not concern ourselves with all the variations.

That ends our introductory discussion of stacks and queues. Now let's look at some examples.

9.2.1. Implementing a Stricter Stack

We promised earlier to show how a stack could be made "idiot-proof" against illegal access. We may as well do that now. Here is a simple class that has an internal array and manages access to that array. (There are other ways of doing thisby delegating, for examplebut what we show here is simple and works fine.)

class Stack

  def initialize
    @store = []
  end

  def push(x)
    @store.push x
  end

  def pop
    @store.pop
  end

  def peek
    @store.last
  end

  def empty?
    @store.empty?
  end

end

We have added one more operation that is not defined for arrays; peek simply examines the top of the stack and returns a result without disturbing the stack.

Some of the rest of our examples assume this class definition.

9.2.2. Detecting Unbalanced Punctuation in Expressions

Because of the nature of grouped expressions such as parentheses and brackets, their validity can be checked using a stack. For every level of nesting in the expression, the stack will grow one level higher; when we find closing symbols, we can pop the corresponding symbol off the stack. If the symbol does not correspond as expected, or if there are symbols left on the stack at the end, we know the expression is not well-formed.

def paren_match(str)
  stack = Stack.new
  lsym = "{[(<"
  rsym = "}])>"
  str.each_byte do |byte|
    sym = byte.chr
    if lsym.include? sym
      stack.push(sym)
    elsif rsym.include? sym
      top = stack.peek
      if lsym.index(top) != rsym.index(sym)
        return false
      else
        stack.pop
      end
      # Ignore non-grouped characters...
    end
  end
  # Ensure stack is empty...
  return stack.empty?
end

str1 = "(((a+b))*((c-d)-(e*f))"
str2 = "[[(a-(b-c))], [[x,y]]]"

paren_match str1          # false
paren_match str2          # true

The nested nature of this problem makes it natural for a stack-oriented solution. A slightly more complex example would be the detection of unbalanced tags in HTML and XML. The tokens are multiple characters rather than single characters, but the structure and logic of the problem remain exactly the same. Some other common stack-oriented problems are conversion of infix expressions to postfix form (or vice versa), evaluation of a postfix expression (as is done in a Java VM or many other interpreters), and in general any problem that has a recursive solution. In the next section, we'll take a short look at the relationship between stacks and recursion.

9.2.3. Understanding Stacks and Recursion

As an example of the isomorphism between stack-oriented algorithms and recursive algorithms, we will take a look at the classic "Tower of Hanoi" problem.

According to legend, there is an ancient temple somewhere in the far east, where monks have the sole task of moving disks from one pole to another while obeying certain rules about the moves they can make. There were originally 64 disks on the first pole; when they finished, the world would come to an end.

As an aside, we like to dispel myths when we can. It seems that in reality, this puzzle originated with the French mathematician Edouard Lucas in 1883 and has no actual basis in eastern culture. What's more, Lucas himself named the puzzle the "Tower of Hanoi" (in the singular).

So if you were worried about the world ending . . . don't worry on that account. And anyway, 64 disks would take 264-1 moves. A few minutes with a calculator reveals that those monks would be busy for millions of years.

But on to the rules of the game. (We'll explain this even though every first-year computer science student in the world has already seen the puzzle.) We have a pole with a certain number of disks stacked on it; call this the source pole. We want to move all of these to the destination pole, using a third (auxiliary) pole as an intermediate resting place. The catch is that you can only move one disk at a time, and you cannot ever place a larger disk onto a smaller one.

The following example uses a stack to solve the problem. We use only 3 disks because 64 would occupy a computer for centuries.

def towers(list)
  while !list.empty?
    n, src, dst, aux = list.pop
    if n == 1
      puts "Move disk from #{src} to #{dst}"
    else
      list.push [n-1, aux, dst, src]
      list.push [1, src, dst, aux]
      list.push [n-1, src, aux, dst]
    end
  end
end


list = []
list.push([3, "a", "c", "b"])

towers(list)

The output produced here is:

Move disk from a to c
Move disk from a to b
Move disk from c to b
Move disk from a to c
Move disk from b to a
Move disk from b to c
Move disk from a to c

Of course, the classic solution to this problem is recursive. And as we already pointed out, the close relationship between the two algorithms is no surprise because recursion implies the use of an invisible system-level stack.

def towers(n, src, dst, aux)
  if n==1
    puts "Move disk from #{src} to #{dst}"
  else
    towers(n-1, src, aux, dst)
    towers(1, src, dst, aux)
    towers(n-1, aux, dst, src)
  end
end

towers(3, "a", "c", "b")

The output produced here is the same. And it may interest you to know that we tried commenting out the output statements and comparing the runtimes of these two methods. Don't tell anyone, but the recursive version is twice as fast.

9.2.4. Implementing a Stricter Queue

We define a queue here in much the same way we defined a stack earlier. If you want to protect yourself from accessing such a data structure in an illegal way, we recommend this practice.

class Queue

  def initialize
    @store = []
  end

  def enqueue(x)
    @store << x
  end

  def dequeue
    @store.shift
  end

  def peek
    @store.first
  end

  def length
    @store.length
  end

  def empty?
    @store.empty?
  end

end

We should mention that there is a Queue class in the thread library that works very well in threaded code. There is even a SizedQueue variant.

These queues use the method names enq and deq rather than the longer names shown in the preceding example. They also allow the names push and pop, which seems misleading to me. The data structure is FIFO, not LIFO; that is, it is a true queue and not a stack.

Of course, the Queue class in tHRead.rb is thread-safe, which is a good enough reason for it to exist. If you need a thread-safe Stack class, I recommend you take the Queue class as a starting point. This should be a quick and easy fix.

The first edition of this book had a lengthy example of queue usage here. Like some of the stack examples, it has been omitted from this edition to save space.

评论

相关推荐

    Python Tutorial 入门指南3.6英文版

    9.2. Python Scopes and Namespaces 91 9.2.1. Scopes and Namespaces Example 94 9.3. A First Look at Classes 95 9.3.1. Class Definition Syntax 95 9.3.2. Class Objects 96 9.3.3. Instance Objects 97 9.3.4....

    python3.6.5参考手册 chm

    PEP 492 - Coroutines with async and await syntax PEP 465 - A dedicated infix operator for matrix multiplication PEP 448 - Additional Unpacking Generalizations PEP 461 - percent formatting support ...

    The Algorithm Design Manual (2rd Edition)

    3.2 Stacks and Queues 3.3 Dictionaries 3.4 Binary Search Trees 3.5 Priority Queues 3.6 War Story: Stripping Triangulations 3.7 Hashing and Strings 3.8 Specialized Data Structures 3.9 War Story...

    基于物联网智能化平台的智慧园区解决方案PPT(28页).pptx

    智慧园区,作为现代城市发展的新形态,旨在通过高度集成的信息化系统,实现园区的智能化管理与服务。该方案提出,利用智能手环、定制APP、园区管理系统及物联网技术,将园区的各类设施与设备紧密相连,形成一个高效、便捷、安全的智能网络。从智慧社区到智慧酒店,从智慧景区到智慧康养,再到智慧生态,五大应用板块覆盖了园区的每一个角落,为居民、游客及工作人员提供了全方位、个性化的服务体验。例如,智能手环不仅能实现定位、支付、求助等功能,还能监测用户健康状况,让科技真正服务于生活。而智慧景区的建设,更是通过大数据分析、智能票务、电子围栏等先进技术,提升了游客的游玩体验,确保了景区的安全有序。 尤为值得一提的是,方案中的智慧康养服务,展现了科技对人文关怀的深刻体现。通过智慧手环与传感器,自动感知老人身体状态,及时通知家属或医疗机构,有效解决了“空巢老人”的照护难题。同时,智慧生态管理系统的应用,实现了对大气、水、植被等环境要素的实时监测与智能调控,为园区的绿色发展提供了有力保障。此外,方案还提出了建立全域旅游营销平台,整合区域旅游资源,推动旅游业与其他产业的深度融合,为区域经济的转型升级注入了新的活力。 总而言之,这份智慧园区建设方案以其前瞻性的理念、创新性的技术和人性化的服务设计,为我们展示了一个充满智慧与活力的未来园区图景。它不仅提升了园区的运营效率和服务质量,更让科技真正融入了人们的生活,带来了前所未有的便捷与舒适。对于正在规划或实施智慧园区建设的决策者而言,这份方案无疑提供了一份宝贵的参考与启示,激发了他们对于未来智慧生活的无限遐想与憧憬。

    MES制造企业生产过程执行系统:全方位协同管理,提升生产效率与质量的信息化管理平台,MES制造企业生产过程执行系统:全面协同管理,提升生产效率与质量管理水平,mes制造企业生产过程执行系统,是一套面向

    MES制造企业生产过程执行系统:全方位协同管理,提升生产效率与质量的信息化管理平台,MES制造企业生产过程执行系统:全面协同管理,提升生产效率与质量管理水平,mes制造企业生产过程执行系统,是一套面向制造企业车间执行层的生产信息化管理系统。 MES 可以为企业提供包括制造数据管理、计划排产管理、生产调度管理、库存管理、质量管理、人力资源管理、工作中心 设备管理、工具工装管理、采购管理、成本管理、项目看板管理、生产过程控制、底层数据集成分析、上层数据集成分解等管理模块,为企业打造一个扎实、可靠、全面、可行的制造协同管理平台 ,MES制造企业生产过程执行系统;生产信息化管理;制造数据管理;计划排产管理;生产调度管理;库存管理;质量管理;人力资源管理;设备管理;数据集成分析,MES制造企业生产执行系统:全面协同管理平台助力制造企业高效运营

    C++指针与内存管理详解:避免常见错误及最佳实践

    内容概要:本文介绍了C++编程中常见指针错误及其解决方案,并涵盖了模板元编程的基础知识和发展趋势,强调了高效流操作的最新进展——std::spanstream。文章通过一系列典型错误解释了指针的安全使用原则,强调指针初始化、内存管理和引用安全的重要性。随后介绍了模板元编程的核心特性,展示了编译期计算、类型萃取等高级编程技巧的应用场景。最后,阐述了C++23中引入的新特性std::spanstream的优势,对比传统流处理方法展现了更高的效率和灵活性。此外,还给出了针对求职者的C++技术栈学习建议,涵盖了语言基础、数据结构与算法及计算机科学基础领域内的多项学习资源与实战练习。 适合人群:正在学习C++编程的学生、从事C++开发的技术人员以及其他想要深入了解C++语言高级特性的开发者。 使用场景及目标:帮助读者掌握C++中的指针规则,预防潜在陷阱;介绍模板元编程的相关技术和优化方法;使读者理解新引入的标准库组件,提高程序性能;引导C++学习者按照有效的路径规划自己的技术栈发展路线。 阅读建议:对于指针部分的内容,应当结合实际代码样例反复实践,以便加深理解和记忆;在研究模板元编程时,要从简单的例子出发逐步建立复杂模型的理解能力,培养解决抽象问题的能力;而对于C++23带来的变化,则可以通过阅读官方文档并尝试最新标准特性来加深印象;针对求职准备,应结合个人兴趣和技术发展方向制定合理的学习计划,并注重积累高质量的实际项目经验。

    VSC下垂控制策略仿真模型:基于MATLAB 2014a及更高版本的全面支持与应用实践,VSC下垂控制策略仿真模型MATLAB版本支持及功能解析,VSC下垂控制策略仿真模型,支持MATLAB2014a

    VSC下垂控制策略仿真模型:基于MATLAB 2014a及更高版本的全面支持与应用实践,VSC下垂控制策略仿真模型MATLAB版本支持及功能解析,VSC下垂控制策略仿真模型,支持MATLAB2014a及以上版本 ,VSC下垂控制策略; 仿真模型; MATLAB 2014a及以上版本; 核心关键词,MATLAB 2014a及以上版VSC下垂控制策略仿真模型研究

    信息技术知识赛系统设计与实现(代码+数据库+LW)

    摘  要 传统办法管理信息首先需要花费的时间比较多,其次数据出错率比较高,而且对错误的数据进行更改也比较困难,最后,检索数据费事费力。因此,在计算机上安装信息技术知识赛系统软件来发挥其高效地信息处理的作用,可以规范信息管理流程,让管理工作可以系统化和程序化,同时,信息技术知识赛系统的有效运用可以帮助管理人员准确快速地处理信息。 信息技术知识赛系统在对开发工具的选择上也很慎重,为了便于开发实现,选择的开发工具为Eclipse,选择的数据库工具为Mysql。以此搭建开发环境实现信息技术知识赛系统的功能。其中管理员管理用户,新闻公告。 信息技术知识赛系统是一款运用软件开发技术设计实现的应用系统,在信息处理上可以达到快速的目的,不管是针对数据添加,数据维护和统计,以及数据查询等处理要求,信息技术知识赛系统都可以轻松应对。 关键词:信息技术知识赛系统;SpringBoot框架,系统分析,数据库设计

    蓝桥杯python准备建议.zip

    蓝桥杯是全国范围内具有广泛影响力的编程竞赛,对于准备参加蓝桥杯 Python 组比赛的同学来说,系统化的学习和针对性的训练是取得好成绩的关键。本项目是一份详细的蓝桥杯 Python 组准备建议,涵盖基础知识、算法与数据结构、刷题策略、实战演练以及心态调整等方面。

    Simulink与Carsim联合仿真实现轨迹跟踪,考虑侧倾、曲率变化及侧偏刚度修正,考虑侧倾和曲率变化的轨迹跟踪:Simulink与Carsim联合仿真修正侧偏刚度技术解析,轨迹跟踪,考虑侧倾和曲率

    Simulink与Carsim联合仿真实现轨迹跟踪,考虑侧倾、曲率变化及侧偏刚度修正,考虑侧倾和曲率变化的轨迹跟踪:Simulink与Carsim联合仿真修正侧偏刚度技术解析,轨迹跟踪,考虑侧倾和曲率变化,同时修正侧偏刚度 simulink carsim联合仿真 ,轨迹跟踪; 侧倾和曲率变化; 侧偏刚度修正; Simulink; CarSim联合仿真,Simulink联合仿真:车辆轨迹跟踪及侧倾、曲率修正研究

    Unity-游戏开发-模型资源-科幻武器

    总共包含 32 款 AAA 级科幻武器。四种武器类型,每种有 8 种不同的纹理变化! 所有内容均采用 PBR 材质,可直接用于开发游戏!

    Linux环境下PyTorch深度学习框架的搭建指南(Anaconda、CUDA、PyCharm、Jupyter)

    内容概要:本文详细介绍了在Ubuntu Linux上如何从零开始构建完整的PyTorch深度学习环境。步骤涵盖了镜像源配置、必需环境安装、Anaconda安装及配置,CUDA和显卡驱动安装,Anaconda虚拟环境创建,PyTorch安装及其相关依赖库的安装方法。对于安装过程中可能出现的一些问题提供了相应的解决方案。此外还简要涉及了Python环境的维护、IDE PyCharm的安装方法以及如何启动Anaconda附带的Jupyter Notebook。 适合人群:希望深入了解Linux操作系统下的机器学习环境配置过程的初级开发者和技术爱好者,特别是有兴趣应用PyTorch从事科研项目的人群。 使用场景及目标:旨在帮助读者掌握基于Ubuntu平台配置高性能PyTorch环境的具体流程,从而能快速投入到实际开发工作中;同时为未来扩展更多AI/ML应用打下坚实基础。 其他说明:本教程假设读者已经有一定Linux命令行操作基础,并且拥有基本的Python编程能力。教程重点在于具体的技术步骤而非理论讲解,对于每一阶段都附带有详尽的操作截图辅助理解。

    IEEE9节点系统Simulink仿真:实现潮流计算与稳定性分析的电力仿真模型,基于Matlab Simulink的IEEE9节点系统仿真:潮流计算与稳定性分析,IEEE9节点系统Simulink仿真

    IEEE9节点系统Simulink仿真:实现潮流计算与稳定性分析的电力仿真模型,基于Matlab Simulink的IEEE9节点系统仿真:潮流计算与稳定性分析,IEEE9节点系统Simulink仿真 1.基础功能:基于Matlab simulink平台搭建IEEE9节点仿真模型,对电力系统进行潮流计算(与编程用牛拉法计算潮流结果一致) 2.拓展功能: 可在该IEEE9节系统仿真模型上进行暂态、静态稳定性仿真分析。 ,IEEE9节点系统; Simulink仿真; 潮流计算; 牛拉法; 暂态稳定性仿真分析; 静态稳定性仿真分析,基于Simulink的IEEE9节点系统仿真:潮流计算与稳定性分析

    欧姆龙NJ/NX系列PLC ST语言编程:Modbus RTU读写轮询与八从站通讯集成,搭配CF105模块使用,含FB功能块调用案例参考,欧姆龙NJ/NX系列PLC的ST语言编程:集成Modbus R

    欧姆龙NJ/NX系列PLC ST语言编程:Modbus RTU读写轮询与八从站通讯集成,搭配CF105模块使用,含FB功能块调用案例参考,欧姆龙NJ/NX系列PLC的ST语言编程:集成Modbus RTU读写轮询与八个485从站通讯功能,搭配CF105模块使用,含通讯FB功能块与主程序调用案例,欧姆龙NJ,NX系列plc,ST语言编写,该程序包含ModbusRTU的读写轮询,带八个485从站,此程序必须搭配欧姆龙CF105模块才能使用。 通讯的程序都封装成FB功能块可以直接调用,主程序有调用案例参考 ,欧姆龙NJ; NX系列PLC; ST语言编写; ModbusRTU读写轮询; 485从站; 欧姆龙CF105模块; 通讯FB功能块; 主程序调用案例。,欧姆龙PLC ST语言Modbus RTU读写轮询程序:CF105模块八从站通讯应用

    数学建模相关主题资源2

    数学建模相关主题资源2

    Go语言教程&案例&相关项目资源

    Go语言教程&案例&相关项目资源

    企业微信会话存档+deepseek智能预警

    ### **软件更新公告:AI会话存档与分析功能全新上线!** 亲爱的用户, 我们很高兴地宣布,本次软件更新带来了全新的 **AI会话存档与分析功能**,旨在帮助企业更好地管理员工与客户的沟通内容,提升服务质量,优化运营效率。以下是本次更新的详细内容: --- #### **1. 会话存档** - **功能描述**:系统将自动拉取员工与客户的文本聊天内容,并完整存档,方便随时查阅。 - **使用场景**: - 查看员工与客户的历史沟通记录。 - 审计聊天内容,确保合规性。 - 为客户问题提供追溯依据。 --- #### **2. AI会话报告** - **功能描述**:结合 **DeepSeek AI** 技术,对员工发送给客户的聊天内容进行智能分析,判断是否存在以下行为: - **敲单行为**:识别员工是否诱导客户下单或进行不必要的推销。 - **辱骂客户**:检测聊天内容中是否存在不当言辞或辱骂行为。 - **索要回扣/红包**:分析员工是否向客户索要回扣、红包或其他不当利益。 - **使用场景**: - 实时监控员工与客户的沟通质量。

    点餐系统.zip

    毕业设计

    并联型APF有源电力滤波器Matlab Simulink仿真研究:涉及dq和αβ坐标系谐波无功检测与SVPWM调制方式的仿真介绍文档,基于Matlab Simulink仿真的并联型APF有源电力滤波器

    并联型APF有源电力滤波器Matlab Simulink仿真研究:涉及dq和αβ坐标系谐波无功检测与SVPWM调制方式的仿真介绍文档,基于Matlab Simulink仿真的并联型APF有源电力滤波器谐波及无功检测技术研究,包含PI控制与SVPWM调制方式的深入探讨,并联型APF 有源电力滤波器 Matlab Simulink仿真 *dq FBD谐波 无功检测 *两相旋转坐标系(dq)、两相静止坐标系(αβ)下的PI控制 *SVPWM调制方式 (含仿真介绍文档) ,核心关键词:并联型APF; 有源电力滤波器; Matlab Simulink仿真; dq FBD谐波无功检测; 两相旋转坐标系PI控制; 两相静止坐标系PI控制; SVPWM调制方式。,基于Matlab Simulink仿真的并联型APF有源电力滤波器研究:dq FBD谐波与无功检测的PI控制及SVPWM调制方式

    Swift编程语言详解:从基础语法到Swift 6新特性及跨平台发展趋势

    内容概要:本文详细介绍了苹果公司推出的编程语言 Swift,涵盖其基本概念、语法特点、环境搭建以及从 Swift 3 到 Swift 6 的重要更新与发展历程。Swift 是一门专注于 iOS、macOS、watchOS 和 tvOS 开发的语言,语法简洁,比 Objective-C 更易于学习和使用。文章首先简要介绍了 Swift 的基础知识,包括变量和常量、基本数据类型、控制流语句、函数定义、类和结构体,以及高级特性如可选类型、强制解包、可选绑定、闭包和协议。接着探讨了 Swift 的历史演变及其在不同操作系统(Linux 和 Windows)上的应用,尤其是 Swift 在 2015 年开源后的快速发展。最新的 Swift 6 版本引入了诸如编译时数据竞争保护等多项创新特性,极大地提升了并发编程的安全性和易用性。最后讨论了开发者的看法及其应用场景的可能性。 适合人群:具有一定编程基础的研发人员,尤其是那些有兴趣深入了解苹果生态系统或跨平台开发的技术爱好者。 使用场景及目标:帮助读者快速掌握 Swift 编程语言的核心概念和技术栈;指导初学者如何配置和使用 Xcode 编写首个 Swift 应用程序;分析最新发布的 Swift 6 更新亮点,并提供从 Swift 5 迁移到 Swift 6 期间可能遇到的问题及解决方法。 阅读建议:建议新手先掌握基本的 Swift 语法和面向对象编程思想再深入研究高级主题;同时密切关注官方发布的最新动态和支持资料,及时更新对 Swift 技术的认知;针对想要过渡到 Swift 6 的团队,务必进行充分的学习准备并在实践中积累经验以克服潜在困难。此外,考虑到 Swift 正逐渐扩展到非苹果平台的应用开发中,请对 Swift 在不同平台下的表现保持敏感并积极探索跨平台解决方案。

Global site tag (gtag.js) - Google Analytics