第6週実践プロジェクト1—順序スタックアルゴリズムライブラリの構築

3593 ワード

/* 
Copyright (c)2015,               
All rights reserved. 
    :  1.cbp 
      :   
    :2015 12 1  
     :v1.0 
 
 
    :         ,       ,     。 
    :  
    :     
*/  
sqstack.hファイルコード:
#ifndef SQSTACK_H_INCLUDED  
#define SQSTACK_H_INCLUDED  
  
  
#define MaxSize 100  
#include <stdio.h>  
#include <malloc.h>  
typedef char ElemType;  
typedef struct  
{  
    ElemType data[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);  //     
  
  
#endif // SQSTACK_H_INCLUDED 
sqstack.cpp    :
<pre name="code" class="cpp">//           
#include "sqstack.h"  
  
  
//      
void InitStack(SqStack *&s)  
{  
    s=(SqStack *)malloc(sizeof(SqStack));  
    s->top=-1;               //      -1  
}  
//     
void DestroyStack(SqStack *&s)  
{  
    free(s);                 //       
}  
//        ——     
int StackLength(SqStack *s)  
{  
    return(s->top+1);  
}  
//       
bool StackEmpty(SqStack *s)  
{  
    return(s->top==-1);  
}  
//    
bool Push(SqStack *&s,ElemType e)  
{  
    if (s->top==MaxSize-1)    //     ,       
        return false;  
    s->top++;                 //     1  
    s->data[s->top]=e;        //  e         
    return true;  
}  
//    
bool Pop(SqStack *&s,ElemType &e)  
{  
    if (s->top==-1)     //      ,       
        return false;  
    e=s->data[s->top];  //       
    s->top--;           //     1  
    return true;  
}  
//       
bool GetTop(SqStack *s,ElemType &e)  
{  
    if (s->top==-1)         //      ,       
        return false;  
    e=s->data[s->top];      //       
    return true;  
}  
//     
void DispStack(SqStack *s)  
{  
    int i;  
    for (i=s->top;i>=0;i--)  
        printf("%c ",s->data[i]);  
    printf("
"); }
main.cppファイルコード:
 
 
<pre name="code" class="cpp">[cpp] view plaincopy
#include "sqstack.h"  
  
  
int main()  
{  
    ElemType e;  
    SqStack *s;  
    printf("(1)    s
"); InitStack(s); printf("(2) %s
",(StackEmpty(s)?" ":" ")); printf("(3) a,b,c,d,e
"); Push(s,'a'); Push(s,'b'); Push(s,'c'); Push(s,'d'); Push(s,'e'); printf("(4) %s
",(StackEmpty(s)?" ":" ")); printf("(5) :%d
",StackLength(s)); printf("(6) :");DispStack(s); printf("(7) :"); while (!StackEmpty(s)) { Pop(s,e); printf("%c ",e); } printf("
"); printf("(8) %s
",(StackEmpty(s)?" ":" ")); printf("(9)
"); DestroyStack(s); return 0; }
実行結果:
 
 
<img src="http://img.blog.csdn.net/20151201102312044" alt="" />