順序棧的基本操作實現


基本接口實現代碼,歡迎補充

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TRUE   1
#define FALSE  0
#define OK     1
#define ERROR  0
#define IBFEASIBLE  -1
#define OVERFLOW    -2 

//#define MAXLEN  20
//#define MAXSIZE 20

typedef int Status;
typedef int ElemType; /* 元素類型為int類型*/

//順序棧類型 
typedef struct{
    ElemType *elem;  //存儲空間的基址 
    ElemType *top;        //棧頂位標 
    int size;        //當前分配的存儲容量 
    int increment;    //擴容 
} SqStack;            //順序棧 //順序棧的基本接口實現
 

//1.初始化順序棧 
Status InitStack(SqStack &S,int size,int inc){
    S.elem=(ElemType*)malloc(size*sizeof(ElemType));
      if(S.elem==NULL)
      return OVERFLOW;
      S.top=S.elem;            //置S為空棧
      S.size=size;        //初始容量值
      S.increment=inc;    //初始增量值
      return OK;
}

//2.銷毀順序棧 
Status DestroyStack(SqStack &S){
    free(S.elem);
    S.elem=NULL;
    S.top=NULL;
    S.size=0;
    return OK;
}

//3.判斷棧是否為空,為空返回 
Status StackEmpty(SqStack &S){
    if(S.top==S.elem){
        return TRUE;
    }else{
        return FALSE;
    }
} 

//4.清空棧S
Status ClearStack(SqStack &S){
    S.top=S.elem;
    return OK;
} 

//5.入棧操作S
 Status Push(SqStack &S,ElemType e){
    ElemType *newbase;  //創建一個新的指針
      if(S.top-S.elem>=S.size){
        newbase=(ElemType*)realloc(S.elem,(S.size+S.increment)*sizeof(ElemType));//運用realloc函數進行擴容
    if(newbase=NULL) return OVERFLOW;//擴容失敗
      S.elem=newbase;
      S.top=S.elem+S.size;
      S.size+=S.increment;
    }
      *S.top++=e;
      return OK;
}

//6.出棧
Status Pop(SqStack &S, ElemType &e){
    if(S.top == S.elem) return ERROR;  
    e = * --S.top;  
    return OK;  
} 

//7.取棧頂元素
Status GetTop(SqStack S,ElemType &e){
    if(S.top == S.elem) return ERROR;  
    e = *(S.top -1);  
    return OK;  
}

//8.訪問函數
Status visit(ElemType e){
    printf("%6d",e);
    return OK;
} 

//9.棧遍歷
Status StackTravel(SqStack S,Status (*visit)(ElemType)){
    //對棧用visit()遍歷
    while(S.top>S.elem){
        visit (*(--S.top));
    }                     
    return OK;
}

 覺得有用將點贊哦! 
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM