資料結構之棧的基本操作
阿新 • • 發佈:2018-12-13
本文章包括了棧的建立,初始化,入棧,出棧,清除,銷燬,大小等
+棧的應用(進位制轉換)
- 棧的建立
typedef struct SqStack
{
ElemType *bottom;//棧底指標
ElemType *top;//棧頂指標
int stacksize;//當前大小
}SqStack;
- 棧的初始化
void Init_Stack(SqStack *S) { S->bottom=(ElemType *)malloc(STACK_SIZE*sizeof(ElemType)); if(!S->bottom)//n沒有記憶體時 退出 exit (0); S->top=S->bottom;//初始化,棧頂和棧底指向同一處 S->stacksize=STACK_SIZE;棧的大小 }
- 入棧
void Push_Stack(SqStack *S,ElemType e) { if(S->top-S->bottom>=S->stacksize-1)//棧滿時 { S->bottom=(ElemType *)realloc(S->bottom,(STACKINCREMENT+S->stacksize)*sizeof(ElemType)); if(!S->bottom)//沒有記憶體時退出 exit (0); S->top=S->bottom+S->stacksize;棧頂指標指向 S->stacksize+=STACKINCREMENT;棧的大小 } *(S->top)=e;將值賦給棧頂指標所指位置 S->top++;棧頂指標上移 }
- 出棧
void Pop_Stack(SqStack *S,ElemType *e)
{
if(S->top==S->bottom)//棧為空時
exit (0);
S->top--;//下移棧頂指標
*e=*(S->top);//賦值
}
- 清除一個棧
void Clear_Stack(SqStack *S)
{
S->top=S->bottom;//將棧頂指標指向棧底
}
- 銷燬一個棧
void Destroy_Stack(SqStack *S) { int i,len; len=S->stacksize;//目前棧的大小 for(i=0;i<len;i++) { free(S->bottom);//一一釋放 S.bottom++; } S->bottom=S->top=NULL;//將棧頂指標和棧底指標都指向空 S->stacksize=0;//大小賦值為0 }
- 進位制轉換
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define STACK_SIZE 100
#define STACKINCREMENT 10
typedef char ElemType;
typedef struct SqStack
{
ElemType *bottom;
ElemType *top;
int stacksize;
}SqStack;
void Init_Stack(SqStack *S)//棧的初始化
{
S->bottom=(ElemType *)malloc(STACK_SIZE*sizeof(ElemType));
if(!S->bottom)
exit (0);
S->top=S->bottom;
S->stacksize=STACK_SIZE;
}
void Push_Stack(SqStack *S,ElemType e)//入棧
{
if(S->top-S->bottom>=S->stacksize-1)
{
S->bottom=(ElemType *)realloc(S->bottom,(STACKINCREMENT+S->stacksize)*sizeof(ElemType));
if(!S->bottom)
exit (0);
S->top=S->bottom+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*(S->top)=e;
S->top++;
}
void Pop_Stack(SqStack *S,ElemType *e)//出棧
{
if(S->top==S->bottom)
exit (0);
S->top--;
*e=*(S->top);
}
void Clear_Stack(SqStack *S)//清除一個棧
{
S->top=S->bottom;
}
void Destroy_Stack(SqStack *S)//銷燬一個棧
{
int i,len;
len=S->stacksize;
for(i=0;i<len;i++)
{
free(S->bottom);
S.bottom++;
}
S->bottom=S->top=NULL;
S->stacksize=0;
}
int Len_Stack(SqStack S)
{
return (S.top-S.bottom);
}
int main()
{
ElemType c;
int i,len;
int sum=0;
SqStack S;
Init_Stack(&S);
printf("please input binary number:(# show end)\n");
scanf("%c",&c);
while(c!='#')
{
Push_Stack(&S,c);
scanf("%c",&c);
}
getchar();
len=Len_Stack(S);
for(i=0;i<len;i++)
{
Pop_Stack(&S,&c);
sum=sum+(c-48)*pow(2,i);//進位制轉換公式
}
printf("result=%d",sum);
return 0;
}
- 執行結果