1.栈的顺序存储结构
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define N 20
typedef struct stack
{
int data[N];
int top;
}STACK;
void push(STACK *stack,int d);
int pop(STACK *stack);
int operate(int a,int b,char op);
int main(){
char word[N];
STACK stack;
stack.top=0;
int d1,d2,d3;
while(scanf("%s",word)==1 && word[0]!='#'){
if(isdigit(word[0])){
d1=atoi(word);
push(&stack,d1);
}else{
d1=pop(&stack);
d2=pop(&stack);
d3=operate(d1,d2,word[0]);
push(&stack,d3);
}
}
d1=pop(&stack);
printf("%d\n",d1);
return 0;
}
void push(STACK *stack,int d){
memcpy(&stack->data[stack->top],&d,sizeof(int));
stack->top+=1;
}
int pop(STACK *stack){
stack->top-=1;
return stack->data[stack->top];
}
int operate(int a,int b,char op){
int res;
switch(op)
{
case'+':
res=a+b;
break;
case'-':
res=a-b;
break;
case'*':
res=a*b;
break;
case'/':
res=a/b;
break;
}
return res;
}
2.栈的链式存储结构
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define N 20
typedef struct stack
{
int data;
struct stack *next;
}STACK;
STACK *push(STACK *top,int d);
STACK *pop(STACK *top);
int operate(int a,int b,char op);
int main(){
char word[N];
STACK *top=NULL;
int d1,d2,d3;
while(scanf("%s",word)==1 && word[0]!='#'){
if(isdigit(word[0])){
d1=atoi(word);
top=push(top,d1);
}else{
d1=top->data;
top=pop(top);
d2=top->data;//当d2=8时,top指向最后一个节点
top=pop(top);//d2=8,接着top=top->next=NULL,最后一个节点所占内存被释放
d3=operate(d1,d2,word[0]);
top=push(top,d3);//最终结果占一个节点,整个链表只剩最终结果的节点
}
}
d1=top->data;
printf("%d\n",d1);
pop(top);//释放最后一个节点所占内存
return 0;
}
STACK *push(STACK *top,int d){
STACK *p=NULL;
p=(STACK *)malloc(sizeof(STACK));
p->data=d;
p->next=top;
top=p;
return top;
}
STACK *pop(STACK *top){
STACK *p;
if(top==NULL){
return NULL;
}else{
p=top;
top=top->next;
free(p);
}
return top;
}
int operate(int a,int b,char op){
int res;
switch(op)
{
case'+':
res=a+b;
break;
case'-':
res=a-b;
break;
case'*':
res=a*b;
break;
case'/':
res=a/b;
break;
}
return res;
}