编码定义的变量在运行时的会存放在内存中的静态存储区、栈区或堆区:
1. 申请一块连续的空间(数组),可以存放在上述的三个区中
2. 申请可变长的空间(链表),只能存放在堆区中
其他所有的数据结构在内存中存放时,都只能是数组或者链表的结构,只是在代码逻辑上怎么使用而已。
栈的使用(后进先出):
计算简单加减乘除式子,代码如下:
#include <iostream>
#include <stack>
#include <malloc.h>
using namespace std;
int calInt(int x, char symbol, int y){
//cout << x << ' ' << symbol << ' ' << y << endl;
switch (symbol){
case '+':
return x+y;
case '-':
return x-y;
case '*':
return x*y;
case '/':
return x/y;
default:
return 0/0;
}
}
int calIntFormula(const char *formula){
stack<char> symbolStack;
char symbol = '(';
symbolStack.push(symbol);
stack<int> numberStack;
int number=0;
for (int i=0; formula[i] != '\0'; i++){
if (formula[i] == '+' || formula[i] == '-'){
//当符合优先级低的出现时,先计算优先级高的符号的式子
while(symbolStack.top() == '*' || symbolStack.top() == '/'){
symbol = symbolStack.top();
symbolStack.pop();
number = numberStack.top();
numberStack.pop();
number = calInt(numberStack.top(), symbol, number);
numberStack.pop();
numberStack.push(number);
}
symbolStack.push(formula[i]);
}else if(formula[i] == '(' || formula[i] == '*' || formula[i] == '/'){
//符号优先级高的,直接压栈
symbolStack.push(formula[i]);
}else if(formula[i] == ')' ){
while (symbolStack.top() != '('){
symbol = symbolStack.top();
symbolStack.pop();
number = numberStack.top();
numberStack.pop();
number = calInt(numberStack.top(), symbol, number);
numberStack.pop();
numberStack.push(number);
}
symbolStack.pop();
}
else {
int num = 0;
while(formula[i]>='0' && formula[i]<='9'){
num*=10;
num += formula[i]-'0';
i++;
}
i--;
numberStack.push(num);
}
}
while (symbolStack.top() != '('){
symbol = symbolStack.top();
symbolStack.pop();
number = numberStack.top();
numberStack.pop();
number = calInt(numberStack.top(), symbol, number);
numberStack.pop();
numberStack.push(number);
}
symbolStack.pop();
return numberStack.top();
}
int main()
{
//char symbolPriority[4][2] = {{'*','1'},{'/','1'},{'+','2'},{'-','2'} };
const char formula[]= "2+3*(1+3*5-60/(4-1))";
cout << calIntFormula(formula) << endl;
return 0;
}
队列的使用(先进先出):
简单消息队列,代码如下:
#include <iostream>
#include <queue>
using namespace std;
char* runQueue(char *str){
queue<char> messageQueue;
for (int i=0; str[i]!='\0'; i++){
messageQueue.push(str[i]);
}
int j=0;
while (!messageQueue.empty()){
str[j++] = messageQueue.front();
messageQueue.pop();
}
str[j] = '\0';
return str;
}
int main()
{
char str[] = "hello world";
cout << runQueue(str) << endl;
return 0;
}