栈的功能的总结:
- 递归的实现是基于栈的
- 四则运算表达式
- 从中缀表达式转为后缀表达式(系统内部实现)。(1)借助辅助栈。(2)遇到数字直接打印。(3)遇到符号,将当前符号与栈顶元素进行优先级比较,如果当前元素优先级高直接入栈,若当前元素优先级低则将栈内元素出栈,直到比栈内元素高为止。(4)遇到左括号无条件入栈,遇右括号栈内依次出栈直到左括号停止。
- 从后缀转为中缀表达式。(1)借助辅助栈。(2)遇到数字入栈。(3)遇符号将栈顶元素下一个和栈顶元素构成表达式。
- 使用两个栈完成队列的功能:一个作为入栈,一个作为出栈,将入栈的元素再压入出栈中,再出栈可实现先进先出。
两个栈完成队列的功能代码如下(gcc编译器):
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int nValue;
struct node *pNext;
}Node;
typedef struct stack
{
Node *pTop;
int Count;
}Stack;
//队列结构体,存放两个栈的指针
typedef struct queue
{
int nCount;
Stack *pStack1;
Stack *pStack2;
}Queue;
//栈初始化
void Init(Stack **pStack)
{
*pStack = (Stack*)malloc(sizeof(Stack));
(*pStack)->Count = 0;
(*pStack)->pTop =