스택이 비어 있으면 새 요소를 스택으로 밀어야합니다. 예
큐 초기화 : 배열, LinkedList, ArrayList 등과 같은 다른 데이터 구조를 큐 대신 사용할 수 있습니다.
메인 스택이 비어 있으면 새 요소를 메인 스택으로 밀어야하거나 원한다면 보조 스택 위에 요소를 밀 수 있습니다.
원래 순서를 복원하십시오 :
보조 스택에서 모든 요소를 팝하고 메인 스택으로 다시 밀어 넣으십시오. 이것은 원래의 요소 순서를 복원합니다
단계
기본 케이스 :
를 사용하여 스택 하단에 요소를 삽입하는 단계입니다.
임시 변수 초기화 :
스택을 통해 반복 할 때 요소를 일시적으로 유지하기 위해 변수를 만듭니다.
전송 요소 : 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>
그런 다음 스택에서 루프 대 팝 요소를 사용하여 해당 요소를 임시 변수에 저장합니다.
새 요소 삽입 : 요소를 삽입 한 후 임시 변수의 요소를 다시 스택으로 밀어 넣습니다.
단계
새 요소를 스택에 밀어 넣으십시오.
요소를 복원하십시오 :
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 프로그램의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

javaachievesplatformincendenceThoughthehoughthejavavirtualmachine (JVM), hittoutModification.thejvmcompileSjavacodeIntOplatform-independentByTecode, whatitTengretsAndexeSontheSpecoS, toplacetSonthecificos, toacketSecificos

javaispowerfuldueToitsplatformincendence, 객체 지향적, RichandardLibrary, PerformanceCapabilities 및 StrongSecurityFeatures.1) Platform IndependenceAllowsApplicationStorunannyDevicesUpportingjava.2) 대상 지향적 프로그래밍 프로모션 Modulara

최고 Java 기능에는 다음이 포함됩니다. 1) 객체 지향 프로그래밍, 다형성 지원, 코드 유연성 및 유지 관리 가능성 향상; 2) 예외 처리 메커니즘, 시도 캐치-패치 블록을 통한 코드 견고성 향상; 3) 쓰레기 수집, 메모리 관리 단순화; 4) 제네릭, 유형 안전 강화; 5) 코드를보다 간결하고 표현력있게 만들기위한 AMBDA 표현 및 기능 프로그래밍; 6) 최적화 된 데이터 구조 및 알고리즘을 제공하는 풍부한 표준 라이브러리.

javaisnotentirelyplatformindent의 의존적 duetojvmvariationsandnativecodeintegration

TheJavavirtualMachine (JVM) isanabstractcomputingmachinecrucialforjavaexecutionasitsjavabytecode, "writeonce, runanywhere"기능을 가능하게합니다

javaremainsagoodlugageedueToitscontinuousevolutionandrobustecosystem.1) lambdaexpressionsenhancececeadeabilitys.2) Streamsallowforefficileddataprocessing, 특히 플레어로드 라트 웨이션

javaisgreatduetoitsplatform incendence, robustoopsupport, extensibraries 및 strongcommunity.1) platforminceptenceviajvmallowscodetorunonvariousplatforms.2) oopeatures inncapsulation, Nheritance, and Polymorphismenblularandscode.3)

Java의 5 가지 주요 특징은 다형성, Lambda Expressions, Streamsapi, 제네릭 및 예외 처리입니다. 1. 다형성을 사용하면 다른 클래스의 물체가 공통 기본 클래스의 물체로 사용될 수 있습니다. 2. Lambda 표현식은 코드를보다 간결하게 만듭니다. 특히 컬렉션 및 스트림을 처리하는 데 적합합니다. 3.StreamSapi는 대규모 데이터 세트를 효율적으로 처리하고 선언적 작업을 지원합니다. 4. 제네릭은 유형 안전 및 재사용 성을 제공하며 편집 중에 유형 오류가 잡히립니다. 5. 예외 처리는 오류를 우아하게 처리하고 신뢰할 수있는 소프트웨어를 작성하는 데 도움이됩니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

Dreamweaver Mac版
시각적 웹 개발 도구

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.