C++ 栈的相关操作

#include<iostream>
#include<string>
#include<cassert>
using std::cin;
using std::cout;
using std::endl;
using std::string;
template<typename Type> class Stack {
private:
    Type *elements;
    int max_size, top_index;
public:
    Stack(int length_input) {
        elements = new Type[length_input];
        max_size = length_input;
        top_index = -1;
    }
    ~Stack() {
        delete[] elements;
    }
    bool push(const Type &element) {
        if (top_index >= max_size - 1) {
            return false;
        }
        top_index++;
        elements[top_index] = element;
        return true;
    }
    bool pop() {
        if (top_index < 0) {
            return false;
        }
        top_index--;
        return true;
    }
    // 请在下面实现输出栈顶方法 top
    Type top(){
        assert(top_index >= 0);
        return elements[top_index];
    }
};
int main() {
    int n, m;
    cin >> n >> m;
    Stack<string> stack(n);
    for (int i = 1; i <= m; i++) {
        int opr;
        cin >> opr;
        if (opr == 0) {
            string element;
            cin >> element;
            if (stack.push(element)) {
                cout << "push success!" << endl;
            } else {
                cout << "push failed!" << endl;
            }
        } else if (opr == 1) {
            if (stack.pop()) {
                cout << "pop success!" << endl;
            } else {
                cout << "pop failed!" << endl;
            }
        }else if(opr == 2){
            cout << stack.top() << endl;
        }

    }
    return 0;
}

栈计算表达式(只有加、乘法情况)

#include<iostream>
#include<string>
#include<cassert>
using std::cin;
using std::cout;
using std::endl;
using std::string;
template<typename Type> class Stack {
private:
    Type *elements;
    int max_size, top_index;
public:
    Stack(int length_input) {
        elements = new Type[length_input];
        max_size = length_input;
        top_index = -1;
    }
    ~Stack() {
        delete[] elements;
    }
    bool push(const Type &element) {
        if (top_index >= max_size - 1) {
            return false;
        }
        top_index++;
        elements[top_index] = element;
        return true;
    }
    bool pop() {
        if (top_index < 0) {
            return false;
        }
        top_index--;
        return true;
    }
    Type top() {
        assert(top_index >= 0);
        return elements[top_index];
    }
    bool empty() {
        return top_index < 0;
    }
};
//判断运算优先级
bool precede(char a, char b) {
    if (a == '*' && b == '+') {
        return true;
    } else {
        return false;
    }
}
//加、乘运算
int operate(char theta, int a, int b) {
    if (theta == '+') {
        return a + b;
    } else {
        return a * b;
    }
}
//计算两个栈顶数字的运算
void calc(Stack<int> &numbers, Stack<char> &operators) {
    int a = numbers.top();
    numbers.pop();
    int b = numbers.top();
    numbers.pop();
    numbers.push(operate(operators.top(), a, b));
    operators.pop();
}
int main() {
    int n;
    cin >> n;
    Stack<int> numbers(n);
    Stack<char> operators(n);
    string buffer;
    cin >> buffer;
    int i = 0;
    //将表达式正确地压入数字栈和运算符栈
    while(i < n){
        if (isdigit(buffer[i])){
            numbers.push(buffer[i] - '0');
            i++;
        }else{
        //保证运算符栈顶优先级最高,是的则进行一次出栈运算,不是则把优先级更高的运算符压栈
            if (operators.empty() || precede(buffer[i], operators.top())){
                operators.push(buffer[i]);
                i++;
            }else{
                calc(numbers, operators);
            }
        }
    }
    //计算栈内数字
    while(!operators.empty()){
        calc(numbers, operators);
    }
    cout << numbers.top() << endl;
    return 0;
}

栈计算(±*/)

与上面加乘逻辑不通在于,一般乘除都是选择压栈,但尤其注意!,在栈内已经是除号的情况下,一定要先算栈。否则会出现a/b/c变为a/b*c的情况,因为先算后者:a/(b/c)。

#include<iostream>
#include<string>
#include<cassert>
using std::cin;
using std::cout;
using std::endl;
using std::string;
template<typename Type> class Stack {
private:
    Type *elements;
    int size_max, top_index;
public:
    Stack(int length_input) {
        elements = new Type[length_input];
        size_max = length_input;
        top_index = -1;
    }
    ~Stack() {
        delete[] elements;
    }
    bool push(Type data) {
        if (top_index >= size_max - 1){
            return false;
        }
        top_index++;
        elements[top_index] = data;
        return true;
    }
    bool pop() {
        if (top_index < 0){
            return false;
        }
        top_index--;
        return true;
    }
    Type top() {
        assert(top_index >= 0);
        return elements[top_index];
    }
    bool empty() {
        return top_index < 0;
    }
};
bool precede(char a, char b) {//返回false表示先算栈,true表示压栈
    if (b == '/'){//栈是/时,先算栈
        return false;
    }
    if (a == '*' || a == '/'){
        return true;
    }else{
        return false;
    }
}
float operate(char theta, float a, float b) {
    if (theta == '+'){
        return a + b;
    }else if(theta == '-'){
        return b - a;
    }else if(theta == '*'){
        return a * b;
    }else if(theta == '/'){
        return b / a;
    }
}
void calc(Stack<float> &numbers, Stack<char> &operators) {
    float a = numbers.top();
    numbers.pop();
    float b = numbers.top();
    numbers.pop();
    numbers.push(operate(operators.top(), a, b));
    operators.pop();
}
int main() {
    int num;    
    string buffer;
    cin >> num;
    Stack<float> numbers(num);
    Stack<char> operators(num);
    cin >> buffer;
    int i = 0;
    while(i < num){
        if (isdigit(buffer[i])){
            numbers.push((float)(buffer[i] - '0'));
            i++;
        }else{
            if (operators.empty() || precede(buffer[i], operators.top())){
                operators.push(buffer[i]);
                // cout << "程序1:";
                // cout << numbers.top() << " ";
                // cout << operators.top() << " ";
                // cout <<endl;
                i++;
            }else{
                // cout << "程序2:";
                // cout << numbers.top() << " ";
                // cout << operators.top() << " ";
                // cout << endl;
                calc(numbers, operators);
            }
        }
    }
    // while(!operators.empty()){
    //     cout << operators.top() << " ";
    //     operators.pop();
    // }
    // cout << endl;
    // while(!numbers.empty()){
    //     cout << numbers.top() << " ";
    //     numbers.pop();
    // }
    // cout << endl;
    
    while(!operators.empty()){
        calc(numbers, operators);
    }
    cout << numbers.top() << endl;
    
    return 0;
}

NEW!!

栈的括号匹配问题

在这里插入图片描述

借助递归函数解决(系统栈)

在这里插入图片描述

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

typedef struct Stack{
	int *data;
	int size, top;
}Stack;

Stack *init(int n){
	Stack *s = (Stack *)malloc(sizeof(Stack));
	s->data = (int *)malloc(sizeof(int)* n);
	s->size  = n;
	s->top = -1;
	return s;
}

void clear(Stack *s){
	if (s == NULL) return ;
	free(s->data);
	free(s);
	return;
}

int top(Stack *s){//为空怎么办??
	return s->data[s->top];
}

int empty(Stack *s){
	return s->top == -1;
}

int push(Stack *s, int val){
	if (s == NULL) return 0;
	if (s->top == s->size - 1) return 0;
	//expand
	s->data[++(s->top)] = val;
	return 1;
}

int pop(Stack *s){
	if (s == NULL) return 0;
	if (empty(s)) return 0;
	s->top--;
	return 1;
}

void output(Stack *s){
	printf("Stack(%d) = [", s->top + 1);
	for (int i = 0; i <= s->top; i++){
		i && printf(", ");
		printf("%d", s->data[i]);
	}
	printf("]\n");
	return ;
}

int main(){
	srand(time(0));
#define max_op 20
	Stack *s = init(max_op);
	for (int i = 0; i < max_op; i++){
		int val = rand() % 100;
		push(s, val);
		output(s);
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值