输入数据第一行一个整数N为栈中元素的个数。
接下来一行N个整数表示一个栈依次压入的每个元素。
输出一行表示栈中元素逆序后的栈顶到栈底的每个元素
5 1 2 3 4 5
1 2 3 4 5
import java.util.Scanner;
import java.util.Stack;
public class Main{
// 将stack的栈底元素移除并返回
public static int getAndRemoveLastElement(Stack<Integer> stack){
int result = stack.pop();
if (stack.isEmpty()){
return result;
} else {
int last = getAndRemoveLastElement(stack);
stack.push(result);
return last;
}
}
// 逆序一个栈
public static void reverse(Stack<Integer> stack) {
if (stack.isEmpty()) {
return;
}
int i = getAndRemoveLastElement(stack);
reverse(stack);
stack.push(i);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 迷惑行为:本题的输入是入栈的反顺序,因此借助stackPlus将输入逆序
Stack<Integer> stackInt = new Stack<>();
Stack<Integer> stackPlus = new Stack<>();
while (sc.hasNextInt()){
int N = sc.nextInt();
for (int i = 0; i < N; i++){
stackPlus.push(sc.nextInt());
}
while (!stackPlus.isEmpty()){
stackInt.push(stackPlus.pop());
}
reverse(stackInt);
while (!stackInt.isEmpty()){
System.out.print(stackInt.pop() + " ");
}
}
}
}
void reverse_print(int ptr, int n, int arr[]){
if(ptr < n){
reverse_print(ptr+1, n, arr);
printf("%d ", arr[ptr]);
} else{
return;
}
}
int main(){
int n;
scanf("%d", &n);
int arr[n];
for(int i = 0; i < n; i++){
cin >> arr[i];
}
reverse_print(0, n, arr);
return EXIT_SUCCESS;
}
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
stack.add(reader.nextInt());
}
Fun(stack);
System.out.println();
reader.close();
}
public static void Fun(Stack<Integer> stack) {
//自顶向下打印栈
if (stack.isEmpty()) {
return;
}
int a = stack.pop();
System.out.print(a+" ");
Fun(stack);
}
} 当然也有翻转的实现方式 import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
stack.push(reader.nextInt());
}
Fun2(stack);
Fun(stack);
System.out.println();
reader.close();
}
public static void Fun(Stack<Integer> stack) {
//自底向上打印栈
if (stack.isEmpty()) {
return;
}
int top = stack.pop();
Fun(stack);
System.out.print(top + " ");
}
public static void Fun2(Stack<Integer> stack) {
//翻转函数
if (stack.isEmpty()) {
return;
}
int last = getLast(stack);
Fun2(stack);
stack.push(last);
}
public static int getLast(Stack<Integer> stack) {
//取出栈底元素
int top = stack.pop();
if (stack.isEmpty()) {
return top;
} else {
int last = getLast(stack);
stack.push(top);
return last;
}
}
} #include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
typedef struct {
int *data;
int top;
} stack;
stack *new_stack(int cap);
void push(stack *st, int val);
int pop(stack *st);
bool is_empty(stack *st);
void destroy_stack(stack *st);
int remove_bottom(stack *st);
void reverse_stack(stack *st);
int main(void) {
int n, x;
scanf("%d", &n);
stack *st = new_stack(n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
push(st, x);
}
reverse_stack(st);
while (!is_empty(st)) {
x = pop(st);
printf("%d", x);
if (!is_empty(st))
printf(" ");
}
printf("\n");
destroy_stack(st);
return 0;
}
int remove_bottom(stack *st) {
int x = pop(st);
if (is_empty(st)) {
return x;
}
int next = remove_bottom(st);
push(st, x);
return next;
}
void reverse_stack(stack *st) {
if (is_empty(st)) return;
int bottom = remove_bottom(st);
reverse_stack(st);
push(st, bottom);
}
stack *new_stack(int cap) {
stack *st = (stack *) malloc(sizeof(stack));
st->data = (int *) malloc(sizeof(int) * cap);
st->top = -1;
return st;
}
void push(stack *st, int val) {
st->data[++st->top] = val;
}
int pop(stack *st) {
return st->data[st->top--];
}
bool is_empty(stack *st) {
return st->top == -1;
}
void destroy_stack(stack *st) {
free(st->data);
free(st);
} use std::io::{prelude::*, BufReader};
pub fn get_and_remove_stack_bottom_element(stk: &mut Vec<i32>) -> i32 {
let ans = stk.pop().unwrap();
if stk.is_empty() {
return ans;
} else {
let last = get_and_remove_stack_bottom_element(stk);
stk.push(ans);
return last;
}
}
pub fn reverse_stack(stk: &mut Vec<i32>){
if stk.is_empty() {
return;
}
let i = get_and_remove_stack_bottom_element(stk);
reverse_stack(stk);
stk.push(i);
}
pub fn main() {
let stdin = std::io::stdin();
let handle = stdin.lock();
let mut reader = BufReader::new(handle);
let mut s = String::new();
reader.read_line(&mut s).expect("err");
let n = s.trim().parse::<i32>().expect("err");
s.clear();
reader.read_line(&mut s).expect("err");
let mut stk: Vec<i32> = s.trim().split(' ').map(|x| x.parse().unwrap()).collect();
reverse_stack(&mut stk);
while stk.len() > 0 {
print!("{} ", stk.pop().unwrap());
}
} import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] strArr = br.readLine().split(" ");
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < n; i++) stack.push(Integer.parseInt(strArr[i]));
reverse(stack);
while(!stack.isEmpty()) System.out.print(stack.pop() + " ");
}
private static int getLast(Stack<Integer> stack) {
int result = stack.pop();
if(!stack.isEmpty()){
int last = getLast(stack);
stack.push(result);
return last;
}else
return result; // 只有一个元素,返回去
}
private static void reverse(Stack<Integer> stack) {
if(stack.isEmpty()) return;
int elem = getLast(stack); // 获得栈底
reverse(stack);
stack.push(elem);
}
} import java.util.Stack;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main{
private Stack<Integer> myStack;
public Main(){
this.myStack = new Stack<>();
}
public static void main(String[] args) throws IOException{
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(sc.readLine());
String[] inputData = sc.readLine().split(" ");
Main m = new Main();
for(int i=0;i<num;i++){
m.myStack.push(Integer.parseInt(inputData[num-1-i]));
}
m.reverse(m.myStack);
m.print(m.myStack);
}
public int getandRemoveLast(Stack<Integer> stack){
int result = stack.pop();
if(stack.isEmpty()){
return result;
}
else{
int last = getandRemoveLast(stack);
stack.push(result);
return last;
}
}
public void reverse(Stack<Integer> stack){
if(stack.isEmpty()){
return;
}
else{
int i = getandRemoveLast(stack);
reverse(stack);
stack.push(i);
}
}
public void print(Stack<Integer>stack){
if(stack.isEmpty()){
return;
}
else{
if(stack.size()==1){
System.out.print(stack.pop());
}
else{
System.out.print(stack.pop()+" ");
}
print(stack);
}
}
} private void reverse(Deque<Integer> stack){
if(stack.isEmpty()){
return;
}
int temp = stack.pop();
reverse(stack);
stack.push(temp);
} 没看懂题。。。 直接这么写不行吗
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
Stack<Integer> stack = new Stack<>();
int[] arr = new int[n];
for(int i=0;i<n;i++) {
arr[i] = scanner.nextInt();
}
for(int i=n-1;i>=0;i--) {
stack.push(arr[i]);
}
reverse(stack);
for(int i=0;i<n;i++) {
System.out.print(stack.pop() + " ");
}
}
private static int getAndRemoveLastEle(Stack<Integer> stack) {
int val = stack.pop();
if(stack.isEmpty()) {
return val;
}else {
int res = getAndRemoveLastEle(stack);
stack.push(val);
return res;
}
}
private static void reverse(Stack<Integer> stack) {
if(stack.isEmpty()) {
return;
}
int lastEle = getAndRemoveLastEle(stack);
reverse(stack);
stack.push(lastEle);
}
} #include <algorithm>
#include <stack>
#include <vector>
using namespace std;
int popBottom(stack<int>& sta)
{
int top = sta.top();
sta.pop();
if (sta.empty())return top;
int down = popBottom(sta);
sta.push(top);
return down;
}
void reverseSta(stack<int>&sta)
{
if (sta.size() == 1)return;
int bottom = popBottom(sta);
reverseSta(sta);
sta.push(bottom);
}
int main()
{
int n;
scanf("%d", &n);
stack<int> sta;
for (int i = 0; i < n; i++)
{
int tmp;
scanf("%d", &tmp);
sta.push(tmp);
}
//reverseSta(sta);
while (!sta.empty())
{
int top = sta.top();
sta.pop();
printf("%d ", top);
}
} import sys from collections import deque def pop_bottom(stack): if len(stack) == 1: return stack.pop() num = stack.pop() res = pop_bottom(stack) stack.append(num) return res def reverse(stack): if stack is None or len(stack) == 0: return num = pop_bottom(stack) reverse(stack) stack.append(num) N = int(sys.stdin.readline().strip()) nums = [int(i) for i in sys.stdin.readline().strip().split()] stack = deque() for num in nums: stack.append(num) reverse(stack) while len(stack) > 0: print(stack.popleft(), end=' ')
来一个python能全部跑通的版本
注意: python 的recursion有次数限制, 默认的是1000, 但此处的测试用例的最后一个输入了1500多个数字, 所以要改变默认的限制, 这里保险设置成了2000.
import sys
# python has a recurision limitation
# default is 1000
sys.setrecursionlimit(2000)
def getLastRemove(stack):
res = stack.pop()
if len(stack) == 0:
return res
last = getLastRemove(stack)
stack.append(res)
return last
def reverse(stack):
if len(stack) == 0:
return None
i = getLastRemove(stack)
reverse(stack)
stack.append(i)
return None
stack = []
N = int(input())
a = input()
for i in a.split():
stack.append(int(i))
reverse(stack)
s=""
for i in range(N):
s+= str(stack.pop())
if i < N-1:
s+= " "
print(s)
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.on("line", function (line) {
const tokens = line.split(" ");
if (tokens.length < 2) {
return
}
const list = tokens.map(Number)
const que = []
list.forEach(e => {
f1(que, e)
})
let res = ''
while (que.length) {
res += que.pop() + ' '
}
console.log(res)
});
function f1(que, t) {
if (que.length < 1) {
que.push(t)
return
}
const v = que.pop()
f1(que, t)
que.push(v)
}
准备递归函数f1,和一个保存逆序结果的栈que。每压入一个元素时都通过递归保证que中自栈顶到栈底的元素和压入顺序一样,也就是题目要求的逆序。压入元素e时如果que为空,则直接压入que。如果que非空,则弹出que的栈顶元素,然后递归调用f1(que, e),直到que为空,把e压入que栈底,然后开始返回上层递归,在返回的过程中依次又压回que栈。这样压入1,2,3,4,5后,que中自栈顶到栈底就是1,2,3,4,5
#include <bits/stdc++.h>
using namespace std;
stack<int> st; // 栈
// 递归函数
int dfs(stack<int>& st){
if(st.size() == 1){
int res = st.top();
st.pop();
return res;
}
st.pop();
return dfs(st);
}
int main()
{
int n;
cin >> n;
vector<int> nums(n);
for(int i = 0; i < n; ++i) cin >> nums[i];
for(int i = 0; i < n; ++i){
st.push(nums[i]);
cout << dfs(st) << " " ;
}
return 0;
}