- 实验1:实现顺序栈的各种基本运算的算法
实验内容: 编写一个程序sqstack.cpp,实现顺序栈的各种基本运算(假设顺序栈的元素类型为Elem Type为char),并在次基础上设计一个程序exp2-1.cpp,完成以下功能。
(1)初始化栈s。
(2)判断栈s是否为空。
(3)依次插入a、b、c、d、e。
(4)判断栈s是否为空。
(5)输出出栈序列。
(6)判断栈s是否为空。
(7)释放栈s。
#include <stdio.h>
#include <malloc.h>
#define MaxSize 15
typedef int ElemType;
typedef struct
{ ElemType data[MaxSize];
int top; //栈顶指针
} SqStack;
//(1)初始化栈InitStack(&s)
void InitStack(SqStack *&s)
{ s=(SqStack *)malloc(sizeof(SqStack));
s->top=-1;
}
//(2)销毁栈DestroyStack(&s)
void DestoryStack(SqStack *&s)
{free(s);
}
//(3)判断栈是否为空StackEmpty(s)
bool StackEmpty(SqStack *s)
{ return(s->top==-1);
}
//(4)进栈Push(&s,e)
bool Push(SqStack *&s, ElemType e)
{ if (s->top==MaxSize-1)
return false;
s->top++;
s->data[s->top]=e;
return true;
}
//(5)出栈Pop(&s,&e)
bool Pop(SqStack *&s,ElemType &e)
{ if(s->top==-1)
return false;
e=s->data[s->top];
s->top--;
return true;
}
//(6)取栈顶元素GetTop(s,&e)
bool GetTop(SqStack *s,ElemType &e)
{if (s->top==-1)
return false;
e=s->data[s->top];
return true;
}
int main(){
printf("(1)初始化栈s。\n");
SqStack *st;
InitStack(st);
printf("(2)判断栈s是否为空。\n");
printf(StackEmpty(st)?"空\n":"非空\n");
printf("(3)依次插入a、b、c、d、e。\n");
Push(st,'a');
Push(st,'b');
Push(st,'c');
Push(st,'d');
Push(st,'e');
printf("(4)判断栈s是否为空。\n");
printf(StackEmpty(st)?"空\n":"非空\n");
printf("(5)依次进队d、e、f。\n");
Push(st,'d');
Push(st,'e');
Push(st,'f');
printf("(6)输出出队序列。\n");
int i;
while (st->top!=-1)
{
Pop(st,i);
printf("%c",i);
}
printf("\n");
printf("(7)释放队列q。\n");
DestoryStack(st);
return 1;
}
发表回复