链式栈的初始化:
//结点的信息
struct node
{
ElemType data; //数据域
struct node *next; //指针域
};
typedef struct node Node;
//栈的信息
struct stack
{
Node *top; //头指针
int count; //结点个数
};
typedef struct stack Stack;
int StackInit(Stack **s)
{
(*s) = (Stack *)malloc(sizeof(Stack) * 1);
(*s)->top = NULL;
(*s)->count = 0;
}
初始化只要分配栈信息结构体的空间,结点的空间等到进栈的时候再分配。
进栈:
int push(Stack **s, ElemType e)
{
Node *p = (Node *)malloc(sizeof(Node)); //给结点分配空间
p->data = e; //数据域
p->next = (*s)->top;
(*s)->top = p;
(*s)->count++;
}
出栈:
int pop(Stack **s)
{
Node *p = (*s)->top;
ElemType e = (*s)->top->data;
(*s)->top = (*s)->top->next;
(*s)->count--;
free(p);
}
中缀表达式转后缀表达式,计算带()的表达式
#include <stdio.h>
#include "LinkStack.h"
int Priority(char ch)
{
switch(ch)
{
case '(':
return 3;
case '*':
case '/':
return 2;
case '+':
case '-':
return 1;
default:
return 0;
}
}
int main()
{
Stack *s_opt, *s_num;
char opt[1024] = {0}; //存放表达式
int i = 0, tmp = 0, num1 = 0, num2 = 0;
if (StackInit(&s_opt) != SUCCESS || StackInit(&s_num) != SUCCESS)
{
printf("Init Failure!\n");
}
printf("Please input : \n");
scanf("%s", opt);
while (opt[i] != '\0' || StackEmpty(s_opt) != TRUE) //表达式没结束 或者 操作符栈不为空 一直执行这个循环
{
//输入的时候不是数字就是操作符分两次判断
if (opt[i] >= '0' && opt[i] <= '9') //当输入为数字的时候
{
tmp = tmp * 10 + opt[i] - '0';
i++;
if (opt[i] > '9' || opt[i] < '0') //如果数组后面为操作符时直接入栈,但是如果数字后面还是数字的话就是两位数
{
push(&s_num, tmp); //入栈 写入到接受数字的那个栈
tmp = 0;
}
}
else //如果输入是操作符 分三种情况
{
if (opt[i] == ')' && GetTop(s_opt) == '(') //1.直接出栈不计算
{
pop(&s_opt);
i++;
continue;
}
if (StackEmpty(s_opt) == TRUE || (Priority(opt[i]) > Priority(GetTop(s_opt)))
|| (GetTop(s_opt) == '(' && opt[i] != ')')) //2.进栈
{
push(&s_opt, opt[i]);
i++;
continue;
}
if ((opt[i] == '\0' && StackEmpty(s_opt) != TRUE) ||
(opt[i] == ')' && GetTop(s_opt) != '(') ||
(Priority(opt[i]) <= Priority(GetTop(s_opt)))) //3.出栈计算
{
switch(pop(&s_opt))
{
case '+':
num1 = pop(&s_num);
num2 = pop(&s_num);
push(&s_num, (num1 + num2));
break;
case '-':
num1 = pop(&s_num);
num2 = pop(&s_num);
push(&s_num, (num2 - num1));
break;
case '*':
num1 = pop(&s_num);
num2 = pop(&s_num);
push(&s_num, (num1 * num2));
break;
case '/':
num1 = pop(&s_num);
num2 = pop(&s_num);
push(&s_num, (num2 / num1));
break;
}
}
}
}
printf("%d\n", GetTop(s_num));
return 0;
}
队列:先进先出
//初始化:
struct queue
{
int data[SIZE];
int front; //队头指针(下标)
int rear; //队尾指针
};
typedef struct queue Queue;
int InitQueue(Queue *q)
{
q->rear = q->front = 0; //初始化空队
}
//进队列
int EnterQueue(Queue *q, int e)
{
if ((q->rear + 1) % SIZE == q->front) //队满
{
return FAILURE;
}
q->data[q->rear] = e;
q->rear = (q->rear + 1) % SIZE;
}
//出队列
int DeleteQueue(Queue *q)
{
if (q->rear == q->front)
{
return FAILURE;
}
int e = q->data[q->front];
q->front = (q->front + 1) % SIZE;
return e;
}
//取队头元素
int GetFront(Queue q)
{
if (q.rear == q.front)
{
return FAILURE;
}
return q.data[q.front];
}