C語言棧的實現


static.h

 

#define STATIC_INIT_SIZE 100
#define STATICINCREMENT 10
#define ERROR 0
#define OK 1
typedef struct {

int *base;//定義棧底
int *top;//定義棧頂元素
int staticsize;

}SqStatic;

typedef int Status;

//初始化一個空棧
Status InitStatic(SqStatic *S);

//銷毀棧
Status DestroyStatic(SqStatic *S);

//清空棧
Status ClearStatic(SqStatic *S);

//判斷棧是否為空
Status StaticEmpty(SqStatic S);

//獲取棧的長度
int StaticLength(SqStatic S);

//獲取棧頂元素的值
Status GetTop(SqStatic S, int *e);

//向棧中加入元素
Status Push(SqStatic *S,int e);

//刪除棧頂元素並返回元素值
Status Pop(SqStatic *S, int *e);

void conversion(SqStatic *S)

 

 

StaticRealize.c

 

#include "stdlib.h"
#include "stdio.h"
#include "static.h"


Status InitStatic(SqStatic *S) {

//設置初始棧的大小
S->base = (int *)malloc(sizeof(int)*STATIC_INIT_SIZE);

if (!S->base) {
exit(0);
}
S->top = S->base;//空棧 s->top=s->base
*(S->top) = 0;//主要用來判斷是否為空棧
S->staticsize = STATIC_INIT_SIZE;//棧的初始長度為100

return OK;
}
//獲取棧頂元素的值
Status GetTop(SqStatic S, int *e) {

SqStatic q;
q = S;
//返回棧頂元素需要判斷棧是否為空棧
if (S.base == S.top) return ERROR;

*e = *(q.top - 1);

return OK;

}

//元素的進棧
Status Push(SqStatic *S,int e) {

if ((S->top-S->base)>=S->staticsize) {

S->base = (int *)realloc(S->base,(STATICINCREMENT+STATIC_INIT_SIZE)*sizeof(int));
}
*(S->top) = e;

S->top++;
return OK;

}


Status Pop(SqStatic *S,int *e) {

if (S->top == S->base)return ERROR;

S->top--;
*e = *(S->top);

return OK;

}

Status StaticEmpty(SqStatic S) {
if (*(S.top) == 0) {

return OK;
}
return ERROR;
}


//返回棧中元素的個數
int StaticLength(SqStatic S) {

return S.top - S.base;
}

 

//十進制轉換為二進制

void conversion(SqStatic *S) {

printf("請輸入要轉換的整數\n");
int n;
int e;
scanf("%d",&n);
while (n)
{
int c = n % 2;
Push(S,c);
n =n/2;

}
printf("輸出轉換后的二進制\n");

while (!StaticEmpty(*S))
{
Pop(S,&e);

printf("%d",e);

}
printf("\n");


}

 

 

StaticFunction.c

 

#include "stdio.h"
#include "stdlib.h"
#include "static.h"
//主函數
void main() {

//初始化一個空棧
SqStatic S;

int e,f;

InitStatic(&S);
// printf("判斷棧是否為空棧%d\n", StaticEmpty(S));

Push(&S,1);
GetTop(S, &e);
printf("棧頂元素為%d\n", e);

Push(&S,2);
GetTop(S, &e);
printf("棧頂元素為%d\n", e);

Push(&S,3);
GetTop(S, &e);
printf("棧頂元素為%d\n", e);

Push(&S,4);
GetTop(S, &e);
printf("棧頂元素為%d\n",e);

Pop(&S, &f);

printf("彈出的值為%d\n",f);

Pop(&S, &f);

//10進制轉換為二進制

conversion(&S);

printf("彈出的值為%d\n", f);

printf("判斷棧是否為空棧%d\n", StaticEmpty(S));

printf("棧的長度為%d\n",StaticLength(S));


}

 


免責聲明!

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



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