栈的应用实验

一、实验目的

1、掌握栈的基本概念和后入先出的基本特征。

2、掌握栈的基本操作,包括:栈的初始化、销毁、入栈和出栈操作。

二、实验内容

1、采用顺序表初始化空间大小为 50 个字符的栈。

2、完成下列操作,其中 S 为栈,x,y 为字符型变量。

x = "c"; 
y = "k"; 	
Push(S, x); 
Push(S, "a"); 
Push(S, y); 
Pop(S, x);  
Push(S, "t"); 
Push(S, x); 
Pop(S, x); 
Push(S, "s"); 
while (!SEmpty(S)) 
{ 
	Pop(S, y);
    printf( “%c”, y); 
} 
printf( “%c”, x); 

3、观察输出结果。


#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 50
#define STACKINCREMENT 10
#define ERROR 0
#define OK 1
typedef char SElemType;
typedef struct{
    SElemType *base;
    SElemType *top;
    int stacksize;
}SqStack;


void InitStack(SqStack *S)  //构造一个空栈S
{
    S->base = (SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
    if(!(S->base))
        printf("Oh,no!");
    S->top = S->base;
    S->stacksize = STACK_INIT_SIZE;
}

void Push(SqStack *S, SElemType e)  //插入元素e为新的栈顶元素
{
    if(S->top - S->base >= S->stacksize){
        S->base = (SElemType*)realloc(S->base, (S->stacksize+STACKINCREMENT)*sizeof(SElemType));
        if(!S->base)
            printf("Oh,no!");;
        S->top = S->base + S->stacksize;
        S->stacksize += STACKINCREMENT;
    }
    *S->top++ = e;
}

void Pop(SqStack *S, SElemType *e)  //删除S的栈顶元素
{
    if(S->top == S->base)
        printf("Oh,no!");
    *e = *(--(S->top));
}

SElemType SEmpty(SqStack *S)
{
    if(S->top == S->base)
        return OK;
    else
        return ERROR;
}

SElemType DestroyStack(SqStack *S)
{
    if(S->base){
        free(S->base);
        S->stacksize = 0;
        S->base = S->top = NULL;
    }
    return OK;
}

int main ()
{
    SqStack S;
    SElemType x; 
    SElemType y;    
    x='c';
    y='k';
 
    InitStack(&S);
 
    Push(&S, x); 
    Push(&S, 'a'); 
    Push(&S, y); 
    Pop(&S, &x);  
    Push(&S, 't'); 
    Push(&S, x); 
    Pop(&S, &x); 
    Push(&S, 's'); 
 
    while (!SEmpty(&S)){
        Pop(&S,&y);
        printf("%c", y); 
    } 
    printf("%c", x);
    printf("\n");
 
    DestroyStack(&S);
    return 0;
}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

要告别理想怎算活過

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值