数据结构与算法分析实验4 [进阶]完成简易计算器(较复杂表达式求值),和双端队列、共享栈

表达式求值(通过类实现)基本原理

这里主要通过链式栈进行操作。表达式求值的原理在于将一段复杂的中缀运算转变为前缀表达式、后缀表达式,通过传入的计算序列,创建运算符栈和数值栈,进行运算,通过栈的规则,不断进行以下步骤(以后缀表达式为例):数字入数字栈,运算符入运算符栈,如果符号优先级比已经在栈中的符号优先级高,先进行计算,如果等于或低于前者,从数字栈取出两个数字,符号栈取出前面那个运算符进行运算,结果存放到数字栈中。其难点在于如何比较优先级,如何让处理括号问题。

4.3 表达式求值(类实现)

在后面,或许会利用类的结合特性,给出更好的表达式求值方法,目前阶段主要是进行逻辑思维运算

4.3.1 NodeSatck.h

简单写一个链栈即可

#pragma once
#include<iostream>
typedef int Data;

struct Node {
	Data data;
	Node* next;
};

class NodeSatck {
public:
	NodeSatck();
	~NodeSatck();
	void init();
	void push(Data data);
	Data pop();
	void destory();
	int len();
	Data read();
	void clear();
private:
	int length;
	Node* top;
	Node* base;
};

4.3.2 NodeSatck.cpp

链栈的简单实现,与上一篇博客内容相似

#include"NodeSatck.h"

NodeSatck::NodeSatck() {
	init();
}

NodeSatck::~NodeSatck() {
	destory();
}

void NodeSatck::init() {
	top = new Node;
	base = new Node;
	top->next = base;
	base->next = nullptr;
	length = 0;
}

void NodeSatck::push(Data data) {
	Node* fresh = new Node;
	fresh->data = data;
	fresh->next = top->next;
	top->next = fresh;
	length++;
}

Data NodeSatck::pop() {
	Node* del = top->next;
	top->next = del->next;
	Data data = del->data;
	length--;
	delete del;
	return data;
}

void NodeSatck::destory() {
	length = 0;
	Node* move = top;
	Node* del;
	while (move) {
		del = move;
		move = move->next;
		delete del;
	}
}

int NodeSatck::len() {
	return length;
}

Data NodeSatck::read() {
	if (length == 0) exit(22);
	else {
		return top->next->data;
	}
}

void NodeSatck::clear() {
	Node* move = top->next;
	Node* tmp = nullptr;
	while (move->next != nullptr) {
		tmp = move;
		move = move->next;
		delete tmp;
		length--;
	}
	top->next = base;
}

4.3.3 main.cpp

#include"NodeSatck.h"
using namespace std;
#pragma warning(disable:4996)
float operate(float f, Data opt, float t);
char pre(char a, char b);
int isOperator(char c);
void Optpush();
NodeSatck Op = {};
NodeSatck Val = {};
NodeSatck bExpress = {};
NodeSatck Express = {};
char optr[7] = { '+','-','x','/','(',')','#' };
char prior[7][7] = {
	//+   -   x   /   (   )   #  操作符/栈中
	{'o','o','i','i','i','o','o'},// +
	{'o','o','i','i','i','o','o'},// -
	{'o','o','o','o','i','o','o'},// x
	{'o','o','o','o','i','o','o'},// /
	{'i','i','i','i','i','e','n'},// (
	{'i','i','i','i','e','i','i'},// )
	{'i','i','i','i','i','n','e'} // #
};

int main() {
	Op.push('#');
	//表达式入队列,以两个栈形式完成
	string str;
	cin>>str;
	int length = str.length();
	for (int i = 0; i < length; i++) {
		bExpress.push(str.c_str()[i]);
		cout << bExpress.read() << ' ' << endl;
		cout << i+1<<endl;
	}
	cout << "len:" << bExpress.len() << endl;
	while(bExpress.len()){
		Express.push(bExpress.pop());
		cout << Express.read() << ' ' << endl;
	}
	//表达式入栈操作
	int tmp = 0;
	while (Express.len()!=0) {
		//数字入栈,由于读取的是字符,所以还要处理为数字
		Data ret = (Data)Express.read();
		ret -= '0';
		if (ret >= 0 && ret <= 9) {
			tmp = tmp * 10 + ret ;
			std::cout << "read: "<< ret << std::endl;
			Express.pop();
		}
		else{								//遇到操作符
			if (tmp != 0) {
				Val.push(tmp);				//先将数字传入数字栈
				std::cout << "val push: " << tmp << std::endl;
			}
			tmp = 0;
			//符号入栈,并进行操作
			Op.push(Express.pop());
			Optpush();
		}
	}
	cout << Op.len() << endl;
	std::cout<<Val.pop();
}
float operate(float f, Data opt, float t) {
	cout << "calculating" << endl;
	switch (opt) {
	case '+':return f + t; break;
	case '-':return f - t; break;
	case 'x':return f * t; break;
	case '/':return f / t; break;
	default:exit(-1);
	}
}
//栈中符号,即将入栈符号
char pre(char a, char b) {
	int i = 0; int j = 0;
	while (optr[i] != a) i++;
	while (optr[j] != b) j++;
	cout << prior[i][j] << endl;
	return prior[i][j];
}
//判断是否是合法操作符
int isOperator(char c) {
	for (int i = 0; i < 7; i++)
		if (c == optr[i]) {
			return 1;
		}
	return 0;
}
void Optpush() {
	Data a;
	Data ret;
	if (isOperator(Op.read())) {		//如果是符号
		cout << "is operator!" << endl; 
		Data tmp = Op.pop();			//传出运算符
		switch (pre(Op.read(), tmp)) {	//和前一个运算符比较得到优先级
		case 'i':						//如果后一个运算符优先级高
			Op.push(tmp);
			break;
		case 'e':
			Op.pop();
			cout << "equal" << endl;
			break;
		case 'o':
			a = Val.pop();
			ret = (Data)operate(Val.pop(), Op.pop(), a);
			cout << ret << endl;
			Val.push(ret);
			Op.push(tmp);
			cout << "new operator" << endl;
			if (tmp == ')' || tmp == '#') {
				Optpush();
			}
			break;
		case 'n':exit(1);
		}
	}
	else exit(2);
}

4.3.4 程序运行结果(注释掉一些过程输出后)

在这里插入图片描述

4.4共享栈(单文件实现)

一个数组,但是由自下而上生长的栈和自上而下生长的栈组成

4.4.1 main.cpp

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define MAX_DEF_CAPACITY 20 

typedef int Data;
typedef struct _CoStack {
	Data* base;
	Data* top1;
	Data* top2;
}CoStack,*pCostack;
void coInit(CoStack* cos);
void coPush(CoStack* cos, int i, Data add);
Data coPop(CoStack* cos, int i);
Data coRead(CoStack cos, int i);
int* getLen(CoStack);
void coDes(CoStack* cos);

int main() {
	CoStack cos;
	coInit(&cos);
	for (int i = 0; i < 11; i++) {
		coPush(&cos, 1, i);
		coPush(&cos, 2, i);
	}
	int* ret = getLen(cos);
	printf("maxlen:%d  curlen1:%d  curlen2:%d  remain:%d\n",ret[0],ret[1],ret[2],ret[3]);
	for (int i = 0; i < 11; i++) {
		printf("1 pop: %d   ", coPop(&cos, 1));
		printf("2 pop: %d\n", coPop(&cos, 2));
	}
}
void coInit(CoStack* cos){
	cos->base = (Data*)malloc(MAX_DEF_CAPACITY * sizeof(Data));
	cos->top1 = &cos->base[0];
	cos->top2 = &cos->base[MAX_DEF_CAPACITY - 1];
}
void coPush(CoStack* cos, int i, Data add) {
	if (cos->top1-1 == cos->top2) { printf("Full! Invalid push!\n"); return; }
	if (i == 1) {
		cos->top1[0] = add;
		printf("1 push %d   ",add);
		if (++cos->top1 == cos->top2 + 1) printf("Now I'am full!\n");
	}
	else if (i == 2) {
		cos->top2[0] = add;
		printf("2 push %d\n", add);
		if (--cos->top2 == cos->top1 - 1) printf("Now I’m full!\n");
	}
	else exit(-1);
}
Data coPop(CoStack* cos, int i) {
	if (i == 1&& cos->top1!=&cos->base[0]) {
		cos->top1--;
		return cos->top1[0];
	}
	else if (i == 2&&cos->top2!=&cos->base[MAX_DEF_CAPACITY-1]) {
		cos->top2++;
		return cos->top2[0];
	}
	else {
		printf("Invalid pop!\n");
		exit(-3);
	}
}
Data coRead(CoStack cos, int i) {
	if (i == 1)return cos.top1[-1];
	else if (i == 2)return cos.top2[1];
	else { 
		exit(-3);
		return 0;
	}
}
int* getLen(CoStack cos) {
	int ret[4] = {};
	ret[0] = MAX_DEF_CAPACITY;					    //最大容量
	ret[1] = cos.top1 - cos.base;						    //1的容量
	ret[2] = &cos.base[MAX_DEF_CAPACITY-1] - cos.top2;	//2的容量
	ret[3] = cos.top2 - cos.top1 + 1;					    //剩余容量
	return ret;
}
void coDes(CoStack* cos) {
	free(cos->base);
}

4.4.2 当最大容量为20时,效果如下:

在这里插入图片描述

4.5双端队列

4.5.1 DQueue.h:

#pragma once
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>


typedef int Data;
typedef struct _SqStack {
	Data* data;
	int curlen;
}SqStack;

//			我们可以用栈来实现双端队列:
//基础思想:正向入栈和反向出栈可以看作一个队列,
//        反向入栈和正向出栈又可以看作一个队列。
//		  将栈顶看作队头,我们写出如下代码:

typedef struct _SqStack DQueue, * pDQueue;
void fftt(pDQueue dq);//翻转dq
void push_front(DQueue* dq, Data add);
Data pop_front(DQueue* dq);
void push_back(DQueue* dq, Data add);
Data pop_back(DQueue* dq);
//栈操作
void initStack(SqStack* stack);
void push(SqStack* stack, Data data);
Data pop(SqStack* stack);
Data getLast(SqStack stack);
Data getFirst(SqStack stack);
int getLength(SqStack stack);
int isEmpty(SqStack stack);
void clearStack(SqStack* stack);
void destoryStack(SqStack* stack);

4.5.2 DQueue.cpp

void fftt(pDQueue dq){
	Data* fresh = (Data*)malloc(getLength(*dq) * sizeof(Data));
	for (int i = 0; i < dq->curlen; i++) {
		fresh[dq->curlen - 1 - i] = dq->data[i];
	}
	free(dq->data);
	dq->data= fresh;
}

void push_front(DQueue* dq, Data add){
	push(dq, add);
}

Data pop_front(DQueue* dq){
	return pop(dq);
}

void push_back(DQueue* dq, Data add){
	fftt(dq);
	push(dq, add);
	fftt(dq);
}

Data pop_back(DQueue* dq){
	fftt(dq);
	Data del = pop(dq);
	fftt(dq);
	return del;
}

void initStack(SqStack* stack) {
	stack->data = NULL;
	stack->curlen = 0;
}

void push(SqStack* stack, Data data) {
	Data* fresh = (Data*)malloc((stack->curlen + 1) * sizeof(Data));
	for (int i = 0; i < stack->curlen; i++) fresh[i] = stack->data[i];
	stack->data = fresh;
	stack->data[stack->curlen] = data;
	stack->curlen++;
}

Data pop(SqStack* stack)
{
	Data ret;
	if (--stack->curlen >= 0) {
		ret = stack->data[stack->curlen];
	}
	else(exit(-1));
	return ret;
}

Data getLast(SqStack stack)
{
	if (stack.curlen > 0)
		return stack.data[stack.curlen - 1];
	else exit(0);
}

Data getFirst(SqStack stack){
	return stack.data[0];
}

int getLength(SqStack stack)
{
	return stack.curlen;
}

int isEmpty(SqStack stack)
{
	return stack.curlen == 0;
}

void clearStack(SqStack* stack) {
	stack->curlen = 0;
}

void destoryStack(SqStack* stack) {
	stack->curlen = 0;
	free(stack->data);
}

4.5.3 main.cpp

#include"DQueue.h"
int main() {
	DQueue dq = { };
	initStack(&dq);
	printf("前方入队列:\n");
	for (int i = 0; i < 15; i++) {
		push_front(&dq, i); printf("%d ", getLast(dq));
	}
	printf("\n后方入队列:\n");
	for (int i = 7; i < 17; i++) {
		push_back(&dq, i); printf("%d ", getFirst(dq));
	}
	printf("\n队列元素:\n");
	for (int i = 0; i < getLength(dq); i++)printf("%d ", dq.data[i]);
	printf("\n后方出队列\n");
	for (int i = 0; i < 9; i++) {
		printf("%d ", pop_back(&dq)); 
	}
	printf("\n前方出队列\n");
	for (int i = 0; i < 9; i++) {
		printf("%d ", pop_front(&dq));
	}
}

4.5.4 实现效果

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值