第5周实践项目1 顺序栈建立的算法库
生活随笔
收集整理的這篇文章主要介紹了
第5周实践项目1 顺序栈建立的算法库
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
main.cpp
#include <stdio.h>
#include "Sqstack.h"
int main()
{Elemtype e;SqStack *s;printf("(1)初始化棧s\n");InitStack(s);printf("(2)棧為%s\n",(StackEmpty(s)?"空":"非空"));printf("(3)依次進棧元素a,b,c,d,e\n");Push(s,'a');Push(s,'b');Push(s,'c');Push(s,'d');Push(s,'e');printf("(4)棧為%s\n",(StackEmpty(s)?"空":"非空"));printf("(5)棧長度:%d\n",StackLength(s));printf("(6)從棧頂到棧底元素:");DispStack(s);printf("(7)出棧序列:");while (!StackEmpty(s)){Pop(s,e);printf("%c ",e);}printf("\n");printf("(8)棧為%s\n",(StackEmpty(s)?"空":"非空"));printf("(9)釋放棧\n");DestroyStack(s);return 0;
}
sqstack.h
#include <stdio.h>
#define MaxSize 100
typedef char Elemtype;
typedef struct
{Elemtype date[MaxSize];int top;
}SqStack;
void InitStack(SqStack *&s);
void DestroyStack(SqStack *&s); //銷毀棧
bool StackEmpty(SqStack *s); //棧是否為空
int StackLength(SqStack *s); //返回棧中元素個數——棧長度
bool Push(SqStack *&s,Elemtype e); //入棧
bool Pop(SqStack *&s,Elemtype &e); //出棧
bool GetTop(SqStack *s,Elemtype &e); //取棧頂數據元素
void DispStack(SqStack *s); //輸出棧
sqstack.h
#include <stdio.h>
#include <malloc.h>
#include "sqstack.h"
void InitStack(SqStack *&s)
{s=(SqStack *)malloc(sizeof(SqStack));s->top=-1;
}
void DestroyStack(SqStack *&s)
{free(s);
}
int StackLength(SqStack *s)
{return s->top+1;
}
bool StackEmpty(SqStack *s)
{return s->top==-1;//在這兒s->top 用==判斷不能用=
}
bool Push(SqStack *&s,Elemtype e)
{if(s->top==MaxSize-1)return false;//s->top++;s->date[++s->top]=e;return true;
}
bool Pop(SqStack *&s,Elemtype &e)
{if(s->top==-1)return false;e=s->date[s->top--];//s->top--;return true;
}
bool GetTop(SqStack *s,Elemtype &e)
{if(s->top==-1)return false;e=s->date[s->top];return true;
}
void DispStack(SqStack *s)
{int i;for(i=s->top;i>-1;--i)printf("%c",s->date[i]);printf("\n");
}
總結
以上是生活随笔為你收集整理的第5周实践项目1 顺序栈建立的算法库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ACM-ICPC国际大学生程序设计竞赛北
- 下一篇: 第5周实践项目2 链栈的算法库建立