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); } }
使用遞歸
遞歸是將元素插入堆棧底部的另一種方法。在這種方法中,我們將使用遞歸函數從堆棧中彈出所有元素,直到它變為空,一旦變為空,我們將將新元素插入堆棧中,然後將元素推回堆棧中。 >
>步驟這是使用遞歸插入堆棧底部元素的步驟:
- >>基本情況:檢查堆棧是否為空。如果是空的,我們將將新元素推入堆棧。
- >遞歸案例:如果堆棧不是空的,我們將彈出頂部元素並遞歸地調用該函數。
- >還原元素:完成插入新元素後,我們需要將先前彈出的元素推回堆棧中。
>
在上面的程序中,我們定義了一個遞歸函數,該功能插入堆棧底部的新元素,然後我們繼續從堆棧中彈出元素,直到堆棧變為空,然後我們插入了新元素,此後插入,我們將以前的元素還原到堆棧中。
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); } }
使用臨時變量
我們還可以使用臨時變量來實現給定的任務。我們使用此變量在操縱堆棧時存儲元素。此方法很容易,我們可以使用一個簡單的循環實現。
>>步驟
以下是使用臨時變量&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); } }以下是使用隊列 -
在堆棧底部插入元素的步驟
>
初始化一個隊列:創建一個隊列以保持堆棧中的元素。
>
傳輸元素:- 將新元素推入堆棧。
- 還原元素: 排列隊列中的元素,然後將它們推回堆中。
- >示例
- >輸出 以下是上述代碼的輸出 -
- >
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); } }
在此實施中,我們使用隊列在臨時時間內將元素保存。我們首先將現有元素從堆棧轉移到隊列。然後,我們將新元素推入堆棧,並將原始元素從隊列恢復為堆棧>
>注意:>我們可以使用其他數據結構,例如數組,linkedlist,arrayList等。
以上是Java程序將元素插入堆棧的底部的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

testthepdfinanotherapptoderineiftheissueiswiththefileoredge.2.enablethebuilt inpdfviewerbyTurningOff“ eflblyopenpenpenpenpenpdffilesexternally”和“ downloadpdffiles” inedgesettings.3.clearbrowsingdatainclorwearbrowsingdataincludingcookiesandcachedcachedfileresteroresoreloresorelorsolesoresolesoresolvereresoreorsolvereresoreolversorelesoresolvererverenn

容器化Java應用:創建Dockerfile,使用基礎鏡像如eclipse-temurin:17-jre-alpine,複製JAR文件並定義啟動命令,通過dockerbuild構建鏡像並用dockerrun測試本地運行。 2.推送鏡像到容器註冊表:使用dockertag標記鏡像並推送到DockerHub等註冊表,需先登錄dockerlogin。 3.部署到Kubernetes:編寫deployment.yaml定義Deployment,設置副本數、容器鏡像和資源限制,編寫service.yaml創建

Importjava.ioandjava.net.SocketforI/Oandsocketcommunication.2.CreateaSocketobjecttoconnecttotheserverusinghostnameandport.3.UsePrintWritertosenddataviaoutputstreamandBufferedReadertoreadserverresponsesfrominputstream.4.Usetry-with-resourcestoautomati

VSCode中可通過快捷鍵快速切換面板與編輯區。要跳轉至左側資源管理器面板,使用Ctrl Shift E(Windows/Linux)或Cmd Shift E(Mac);返回編輯區可用Ctrl `或Esc或Ctrl 1~9。相比鼠標操作,鍵盤快捷鍵更高效且不打斷編碼節奏。其他技巧包括:Ctrl KCtrl E聚焦搜索框,F2重命名文件,Delete刪除文件,Enter打開文件,方向鍵展開/收起文件夾。

runthewindowsupdatetrubloubleshooterviaSettings>更新&安全> is esseShootsoAtomationfixCommonissues.2.ResetWindowSupDateComponentsByStoppingRealatedServices,RenamingTheSoftWaredWaredWaredSoftwaredSistribution andCatroot2Folders,intrestrestartingthertingthertingtherserviceSteStoceTocle

要有效使用Mockito進行Java單元測試,首先需添加Mockito依賴,Maven項目在pom.xml中加入mockito-core依賴,Gradle項目添加testImplementation'org.mockito:mockito-core:5.7.0';接著通過@Mock註解(配合@ExtendWith(MockitoExtension.class))或mock()方法創建模擬對象;然後使用when(...).thenReturn(...)等方式對模擬對象的方法行為進行存根,也可配置異

AwhileloopinJavarepeatedlyexecutescodeaslongastheconditionistrue;2.Initializeacontrolvariablebeforetheloop;3.Definetheloopconditionusingabooleanexpression;4.Updatethecontrolvariableinsidethelooptopreventinfinitelooping;5.Useexampleslikeprintingnumber

JavaserializationConvertSanObject'SstateIntoAbyTeSteAmForStorageorTransermission,andDeserializationReconstructstheObjectStheObjectFromThstream.1.toenableserialization,aclassMustimustimplementTheSerializableizableface.2.UseObjectObjectObjectObjectOutputputputputputtreamToserialializeanobectizeanobectementeabectenobexpent,savin
