數據結構第六天

一、棧

1、入棧出棧順序:先進後出,後進先出
2、棧按分佈不同分爲
(1)順序棧
在這裏插入圖片描述
(2)鏈式棧
在這裏插入圖片描述

二、隊列

1、隊列與棧的區別在於:棧是先進後出,後進先出。而隊列是先進先出,後進後出。
將棧看作瓶子裝水和倒水的話,可以將隊列看作水龍頭,先進的先出。
2、隊列按分佈不同分爲
(1)鏈式隊列
在這裏插入圖片描述

三、多項式計算器

#include <stdio.h>
#include "stack.h"
#include <stdlib.h>
#include <string.h>

//判斷字符返回FALSE後進行計算
void calc(Stack *s_ope,Stack *s_num)
{	
	int sum1 = GetTop(s_num);			//取出第一個要計算的數
	pop(s_num);
	
	int sum2 = GetTop(s_num);			//取出第二個要計算的數
	pop(s_num);
	
	int ope = GetTop(s_ope);			//取出要運算的符號
	pop(s_ope);
	
	int res;							//保存運算結果
	
	switch(ope)
	{
		case '+':
			res = sum1+sum2;
			break;
		case '-':
			res = sum2-sum1;
			break;
		case '*':
			res = sum1*sum2;
			break;
		case '/':
			res = sum2/sum1;
			break;
		default:
			break;
	}
	push(s_num,res);					//將結果入棧
}


//判斷是否要入棧TRUE爲要入棧,FALSE爲不入棧
BOOL jud(Stack *s_ope,int n)
{	
	if(Null(s_ope))
	{	
		return TRUE;
	}
	int top = GetTop(s_ope);
	switch(top)
	{
		case '+':
		case '-':
			if('*' == n || '/' == n || '(' == n)
				return TRUE;
			break;
		case '*':
		case '/':
			if('(' == n)
				return TRUE;
			break;
		case '(':
			if(')' == n)
			{
				pop(s_ope);
			}
			return TRUE;			//有點問題
			break;
		default:
			break;
	}
	return FALSE;
}


//對字符進行操作
void deal_ope(Stack *s_ope,Stack *s_num,int n)
{
	if(TRUE == jud(s_ope,n))			//返回爲TRUE入棧
	{
		push(s_ope,n);
	}
	else								//返回爲FALSE,不入棧,並對數據進行處理
	{
		while(FALSE == jud(s_ope,n))
		{	
			calc(s_ope,s_num);
		}
		
		if(')' != n)
		{
			push(s_ope,n);
		}	
	}
}

int main()
{	
	char buf[100];
	printf("請輸入要計算的式子\n");
	fgets(buf,100,stdin);
	buf[strlen(buf)-1] = '\0';
	
	char *p = buf;				//用來遍歷數組
	
	Stack s_num;				//創建棧存放數字
	Stack s_ope;				//創建棧存放符號
	Init(&s_num);				//初始化
	Init(&s_ope);
	
	while(*p)
	{
		if(*p >= '0' && *p <= '9')		//數字入棧
		{	
			int tmp = 0;
			while(*p >= '0' && *p <= '9')
			{
				tmp = tmp*10+*p - '0';
				p++;
			}
			push(&s_num,tmp);
			continue;
		}
		
		deal_ope(&s_ope,&s_num,*p);		//字符入棧
		
		p++;
	}
	while (!Null(&s_ope))					//如果字符棧不爲空,說明數據還沒計算玩
		calc(&s_ope,&s_num);
	
	int sum = GetTop(&s_num);			//得到並且打印最終結果
	printf("%d\n",sum);
	
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章