一、开闭原则:对修改关闭,对增加开放。
二、
1.栈:
内核 运行操作系统的相关代码
栈区(后进先出、由操作系统管理) 存储局部变量、函数的形参和返回值、函数调用关系(保护和恢复现场)
堆区 开发人员手动管理的区域,自己申请,自己释放(malloc、relloc)
数据区 data段 已初始化的全局变量、已初始化的静态变量
bss段 未初始化的全局变量、未初始化的静态变量static
字符串常量区 存储字符串常量“hello”
代码区 代码、指令、‘a’一些常量
2.数据结构中的栈结构:
栈:只允许从一端进行数据的插入和删除的线性结构
3.分类
链式栈:以链表的形式实现
顺序栈:满赠栈、空增栈、满减栈、空减栈
满栈、空栈:栈顶是否存有元素
满栈入栈操作:先移动栈顶再入栈数据
空栈入栈操作,先插入数据再移动栈顶
增栈、减栈:
#include"stack.h"
#include<stdio.h>
#include<stdlib.h>
Stack *create_stack()
{
Stack *pstk = malloc(sizeof(Stack));
if(NULL == pstk)
{
return NULL;
}
pstk->ptop=NULL;
pstk->clen=0;
return pstk;
}
int is_empty_stack(Stack *pstk)
{
if(NULL==pstk->ptop)
{
return 1;
}
return 0;
}
int push_stack(Stack *pstk,Data_type data)
{
Stack_node *pnode=malloc(sizeof(Stack_node));
if(NULL==pnode)
{
return -1;
}
pnode->data=data;
pnode->pnext=pstk->ptop;
pstk->ptop=pnode;
pstk->clen+=1;
return 0;
}
int pop_stack(Stack *pstk,Data_type *pdata)
{
if(is_empty_stack(pstk))
{
return 0;
}
Stack_node *tmp=pstk->ptop;
pstk->ptop=tmp->pnext;
if(NULL != pdata)
{
*pdata=tmp->data;
}
free(tmp);
pstk->clen-=1;
return 1;
}
int get_top_stack(Stack *pstk,Data_type *pdata)
{
if(is_empty_stack(pstk))
{
return 0;
}
// Stack_node *tmp=pstk->ptop;
if(NULL !=pdata)
{
*pdata=pstk->ptop->data;
}
return 1;
}
void clear_stack(Stack *pstk)
{
if(is_empty_stack(pstk))
{
return ;
}
Data_type pdata;
while(pstk->ptop != NULL)
{
pop_stack(pstk,NULL);
}
}
void destory_stack(Stack* pstk)
{
if(is_empty_stack(pstk))
{
free(pstk);
}
else
{
clear_stack(pstk);
}
free(pstk);
}
void print_stack(Stack *pstk)
{
Stack_node *p=pstk->ptop;
while(p != NULL)
{
printf("%d %s %d\n",p->data.id,p->data.name,p->data.score);
p=p->pnext;
}
printf("\n");
}
入参:传递给函数的执行条件
出参:将函数执行获得的某个结果传递给被调函数
4.栈的应用:进行四则运算、回文。
*由于主函数中的sum与被调函数的sum在内存中保存在不同地方,所有值传递是错误的法,因此需要采用指针传递地址去修改值。
中缀表达式:运算符在两个操作数之间1 + 2
前缀表达式(波兰表达式):运算符在两个操作数之前+ 1 2
后缀表达式(逆波兰表达式):运算符在两个操作数之后1 2 +