搜索
首页Javajava教程Java程序将元素插入堆栈的底部

堆栈是遵循LIFO(最后,首先)原理的数据结构。换句话说,我们添加到堆栈中的最后一个元素是第一个要删除的元素。当我们将(或推)元素添加到堆栈中时,它们就会放在顶部;即,首先是所有先前添加的元素。

>

可能在某些情况下我们需要在堆栈底部添加一个元素。有多种方法可以在堆栈的底部添加一个元素。它们是 -

  • 使用辅助堆栈
  • 使用递归
  • 使用临时变量
  • 使用队列

使用辅助堆栈

>我们可以在Java中使用辅助堆栈(使用将执行操作的辅助堆栈(使用该辅助堆栈)插入堆栈底部的元素。在这里,我们将使用两个堆栈(一个主堆栈和一个辅助堆栈)在主堆栈底部插入一个元素。

>

>主堆栈将具有原始元素,而辅助堆栈将帮助我们重新排列元素。此方法易于理解。

>步骤

以下是使用辅助堆栈在堆栈底部插入元素的步骤:

  • >>初始化两个堆栈:创建一个主堆栈中推动其中一些元素,然后创建一个辅助堆栈。
  • >
  • 弹出所有元素:然后从主堆栈中删除所有元素,然后将它们推入第二个辅助堆栈。这将有助于我们扭转元素的顺序。
  • >
  • >按下新元素:>一旦主堆栈为空,我们需要将新元素推入主堆栈中,也可以在需要的情况下将元素推到辅助堆栈的顶部。
  • 还原原始顺序:从辅助堆栈中弹出所有元素,然后将它们推回主堆栈。这将恢复元素的原始顺序。>
  • >示例

以下是我们如何使用辅助堆栈在底部添加元素的示例

在上面的程序中,我们首先将元素1、2、3和4推入堆栈。然后,我们将这些元素转移到另一个堆栈中。之后,我们将目标元素插入主堆栈中。最后,我们从辅助堆栈中检索所有元素。

>

import java.util.Stack;
public class InsertAtBottomUsingTwoStacks {    
   public static void insertElementAtBottom(Stack<integer> mainStack, int x) {
      // Create an extra auxiliary stack
      Stack<integer> St2 = new Stack();
      
      /* Step 1: Pop all elements from the main stack 
      and push them into the auxiliary stack */
      while (!mainStack.isEmpty()) {
         St2.push(mainStack.pop());
      }

      // Step 2: Push the new element into the main stack
      mainStack.push(x);

      /* Step 3: Restore the original order by popping each 
      element from the auxiliary stack and push back to main stack */
      while (!St2.isEmpty()) {
         mainStack.push(St2.pop());
      }
   }
   public static void main(String[] args) {
      Stack<integer> stack1 = new Stack();
      stack1.push(1);
      stack1.push(2);
      stack1.push(3);
      stack1.push(4);

      System.out.println("Original Stack: " + stack1);
      insertElementAtBottom(stack1, 0);
      System.out.println("Stack after inserting 0 at the bottom: " + stack1);
   }
}
</integer></integer></integer>

使用递归

Java程序将元素插入堆栈的底部递归是将元素插入堆栈底部的另一种方法。在这种方法中,我们将使用递归函数从堆栈中弹出所有元素,直到它变为空,一旦变为空,我们将将新元素插入堆栈中,然后将元素推回堆栈中。 >

>步骤

这是使用递归插入堆栈底部元素的步骤:
  • >>基本情况:检查堆栈是否为空。如果是空的,我们将将新元素推入堆栈。
  • >递归案例:如果堆栈不是空的,我们将弹出顶部元素并递归地调用该函数。
  • >还原元素:完成插入新元素后,我们需要将先前弹出的元素推回堆栈中。>
>示例

在上面的程序中,我们定义了一个递归函数,该功能插入堆栈底部的新元素,然后我们继续从堆栈中弹出元素,直到堆栈变为空,然后我们插入了新元素,此后插入,我们将以前的元素还原到堆栈中。
import java.util.Stack;
public class InsertAtBottomUsingTwoStacks {    
   public static void insertElementAtBottom(Stack<integer> mainStack, int x) {
      // Create an extra auxiliary stack
      Stack<integer> St2 = new Stack();
      
      /* Step 1: Pop all elements from the main stack 
      and push them into the auxiliary stack */
      while (!mainStack.isEmpty()) {
         St2.push(mainStack.pop());
      }

      // Step 2: Push the new element into the main stack
      mainStack.push(x);

      /* Step 3: Restore the original order by popping each 
      element from the auxiliary stack and push back to main stack */
      while (!St2.isEmpty()) {
         mainStack.push(St2.pop());
      }
   }
   public static void main(String[] args) {
      Stack<integer> stack1 = new Stack();
      stack1.push(1);
      stack1.push(2);
      stack1.push(3);
      stack1.push(4);

      System.out.println("Original Stack: " + stack1);
      insertElementAtBottom(stack1, 0);
      System.out.println("Stack after inserting 0 at the bottom: " + stack1);
   }
}
</integer></integer></integer>

使用临时变量

我们还可以使用临时变量来实现给定的任务。我们使用此变量在操纵堆栈时存储元素。此方法很容易,我们可以使用一个简单的循环实现。

>

>步骤

以下是使用临时变量&lt;插入堆栈底部的元素的步骤

初始化临时变量:

创建一个变量以暂时保留元素,当您通过堆栈迭代时。
  • >传输元素:然后使用循环从堆栈中弹出元素,然后将这些元素存储在临时变量中。
  • >>插入新元素:>一旦我们的堆栈为空,我们就需要将新元素推入堆栈。
  • 还原元素:插入元素后,将元素从临时变量推回堆栈中。>
  • >示例
  • 在此程序中,我们使用临时数组来操纵堆栈时保持元素。然后,我们将新元素插入堆栈中,然后将原始元素还原到堆栈中。
使用队列

在这种方法中,我们将使用队列在堆栈底部插入新元素时暂时保持元素。此方法是管理元素顺序的更好方法。使用队列我们可以在不篡改现有元素的情况下进入堆栈的新元素。

>步骤
import java.util.Stack;
public class InsertAtBottomUsingRecursion {
   public static void insertAtElementBottom(Stack<integer> st, int x) {
      // Base case: If the stack is empty, push the new element
      if (st.isEmpty()) {
         st.push(x);
         return;
      }
      // Recursive case: Pop the top element
      int top = st.pop();
      
      // Call the function recursively
      insertAtElementBottom(st, x);
      
      // Restore the top element into the stack
      st.push(top);
   }
   
   public static void main(String[] args) {
      Stack<integer> st = new Stack();
      st.push(1);
      st.push(2);
      st.push(3);
      st.push(4);
   
      System.out.println("Original Stack: " + st);
      insertAtElementBottom(st, 0);
      System.out.println("Stack after inserting 0 at the bottom: " + st);
   }
}
</integer></integer>
以下是使用队列 -

在堆栈底部插入元素的步骤

>

初始化一个队列:

创建一个队列以保持堆栈中的元素。

>

传输元素:弹出堆栈中的元素,并将它们加入队列。

>插入新元素:
    将新元素推入堆栈。
  • 还原元素:
  • 排列队列中的元素,然后将它们推回堆中。
  • >示例
  • >输出
  • 以下是上述代码的输出 -
  • >
    import java.util.Stack;
    public class InsertAtBottomUsingTwoStacks {    
       public static void insertElementAtBottom(Stack<integer> mainStack, int x) {
          // Create an extra auxiliary stack
          Stack<integer> St2 = new Stack();
          
          /* Step 1: Pop all elements from the main stack 
          and push them into the auxiliary stack */
          while (!mainStack.isEmpty()) {
             St2.push(mainStack.pop());
          }
    
          // Step 2: Push the new element into the main stack
          mainStack.push(x);
    
          /* Step 3: Restore the original order by popping each 
          element from the auxiliary stack and push back to main stack */
          while (!St2.isEmpty()) {
             mainStack.push(St2.pop());
          }
       }
       public static void main(String[] args) {
          Stack<integer> stack1 = new Stack();
          stack1.push(1);
          stack1.push(2);
          stack1.push(3);
          stack1.push(4);
    
          System.out.println("Original Stack: " + stack1);
          insertElementAtBottom(stack1, 0);
          System.out.println("Stack after inserting 0 at the bottom: " + stack1);
       }
    }
    </integer></integer></integer>
    在此实施中,我们使用队列在临时时间内将元素保存。我们首先将现有元素从堆栈转移到队列。然后,我们将新元素推入堆栈,并将原始元素从队列恢复为堆栈

    >

    >注意:>我们可以使用其他数据结构,例如数组,linkedlist,arrayList等。

以上是Java程序将元素插入堆栈的底部的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
JVM性能与其他语言JVM性能与其他语言May 14, 2025 am 12:16 AM

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生产性。1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

Java平台独立性:使用示例Java平台独立性:使用示例May 14, 2025 am 12:14 AM

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允许CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

JVM架构:深入研究Java虚拟机JVM架构:深入研究Java虚拟机May 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM:JVM与操作系统有关吗?JVM:JVM与操作系统有关吗?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java:写一次,在任何地方跑步(WORA) - 深入了解平台独立性Java:写一次,在任何地方跑步(WORA) - 深入了解平台独立性May 14, 2025 am 12:05 AM

Java实现“一次编写,到处运行”通过编译成字节码并在Java虚拟机(JVM)上运行。1)编写Java代码并编译成字节码。2)字节码在任何安装了JVM的平台上运行。3)使用Java原生接口(JNI)处理平台特定功能。尽管存在挑战,如JVM一致性和平台特定库的使用,但WORA大大提高了开发效率和部署灵活性。

Java平台独立性:与不同的操作系统的兼容性Java平台独立性:与不同的操作系统的兼容性May 13, 2025 am 12:11 AM

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允许Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

什么功能使Java仍然强大什么功能使Java仍然强大May 13, 2025 am 12:05 AM

JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

顶级Java功能:开发人员的综合指南顶级Java功能:开发人员的综合指南May 13, 2025 am 12:04 AM

Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用