스택이 비어 있으면 새 요소를 스택으로 밀어야합니다. 예
큐 초기화 : 배열, 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);
}
}
요소를 삽입 한 후 임시 변수의 요소를 다시 스택으로 밀어 넣습니다.
단계
새 요소를 스택에 밀어 넣으십시오.
요소를 복원하십시오 :
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);
}
}
위 내용은 스택 하단에 요소를 삽입하는 Java 프로그램의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!