How can the reverse output be implemented in the C language stack?

To achieve the reverse output of a stack, you can utilize an additional stack. The specific steps are as follows:

  1. Create a stack named stack and an auxiliary stack named tempStack.
  2. Pop all elements of the stack one by one and push them into the auxiliary stack, tempStack.
  3. By popping elements from the auxiliary stack tempStack in order, we can achieve reverse output.

The following is an example code implementation in C language.

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

typedef struct {
    int top;
    int data[MAX_SIZE];
} Stack;

// 初始化栈
void initStack(Stack* stack) {
    stack->top = -1;
}

// 判断栈是否为空
int isEmpty(Stack* stack) {
    return stack->top == -1;
}

// 判断栈是否已满
int isFull(Stack* stack) {
    return stack->top == MAX_SIZE - 1;
}

// 入栈
void push(Stack* stack, int value) {
    if (isFull(stack)) {
        printf("Stack is full.\n");
        return;
    }
    stack->data[++stack->top] = value;
}

// 出栈
int pop(Stack* stack) {
    if (isEmpty(stack)) {
        printf("Stack is empty.\n");
        return -1;
    }
    return stack->data[stack->top--];
}

// 逆序输出栈的元素
void reverseOutput(Stack* stack) {
    Stack tempStack;
    initStack(&tempStack);

    // 将栈的元素依次出栈,入栈到辅助栈中
    while (!isEmpty(stack)) {
        int value = pop(stack);
        push(&tempStack, value);
    }

    // 依次出栈辅助栈的元素,即可实现逆序输出
    while (!isEmpty(&tempStack)) {
        int value = pop(&tempStack);
        printf("%d ", value);
    }
    printf("\n");
}

int main() {
    Stack stack;
    initStack(&stack);

    // 入栈操作
    push(&stack, 1);
    push(&stack, 2);
    push(&stack, 3);
    push(&stack, 4);

    // 逆序输出栈的元素
    reverseOutput(&stack);

    return 0;
}

After running the code above, the output will be: 4 3 2 1, which is the reverse output of the stack.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds