数据结构之栈的基本操作

本文章包括了栈的创建,初始化,入栈,出栈,清除,销毁,大小等

+栈的应用(进制转换)

  • 栈的创建
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;
}
  • 运行结果

猜你喜欢

转载自blog.csdn.net/qq_42735631/article/details/82953397