栈的使用和简单进制转换的应用


栈头文件

/*
 * ADTStack.h
 *
 *  Created on: 2013-5-26
 *      Author: inner
 */
#ifndef ADTSTACK_H_
#define ADTSTACK_H_
#define STACK_INT_SIZE 100
#define STACKINCREMENT 10
typedef int sElemType;
typedef struct{
	sElemType *top;
	sElemType *base;
	int stacksize;
}SqStack;
//初始化
 void InitStack(SqStack *stack);
 //销毁栈
 void DestroyStack(SqStack *stack);
 //入栈
 void Push(SqStack *stack,sElemType elem);
 //出栈
 int pop(SqStack *stack);
 //栈顶元素
 int getTop(SqStack *stack);
 //判断栈是否为空
 int IsEmpty(SqStack *stack);
#endif /* ADTSTACK_H_ */


栈源文件

/*
 * StackMake.c
 *
 *  Created on: 2013-5-26
 *      Author: inner
 */
#include <stdio.h>
#include <stdlib.h>
#include "ADTStack.h"
 void InitStack(SqStack *stack){
	//分配内存空间
	stack->top = (sElemType*)malloc(STACK_INT_SIZE*sizeof(sElemType));
	if(!stack->top)
		exit(1);
	stack->base = stack->top;
	stack->stacksize = STACK_INT_SIZE;
	printf("初始化成功\n");
 }
 void Push(SqStack *stack,sElemType elem){
	 if(stack->top-stack->base>=stack->stacksize){
		 stack->base =(sElemType*)realloc(stack->base,(STACKINCREMENT+STACK_INT_SIZE)*sizeof(sElemType));
	 }
	 *stack->top = elem;
	 ++stack->top;
	 printf("入栈为%d\n",elem);
	 printf("栈大小%d\n",stack->top-stack->base);
 }
  int pop(SqStack *stack){
	  //检查栈是否为空
	  if(stack->top-stack->base == 0){
		  printf("栈为空");
		  exit(0);
	  }
	  int kk;
	  kk = *--stack->top;
      printf("出站为%d\n",kk);
      printf("栈大小%d\n",stack->top-stack->base);
	  return kk;
  }
  int getTop(SqStack *stack){
	  if(IsEmpty(stack))
		  exit(0);
	  int kk = *(--stack->top);
	  printf("栈顶元素为:%d",kk);
	  return kk;
  }
  int IsEmpty(SqStack *stack){
	  if(stack->top-stack->base == 0){
			  printf("栈已经为空");
			  return 1;
		  }
	  return 0;
  }


栈的进制转换执行文件


#include <stdio.h>
#include <stdlib.h>
#include "ADTStack.h"
void conversion(int,int);
int main(void) {
	int a, b;
	printf("输入十进制数\n");
	scanf("%d",&a);
	printf("输入要转换进制\n");
	scanf("%d",&b);
	conversion(a,b);
	return EXIT_SUCCESS;
}

void conversion(int a,int b){
	SqStack S;
	InitStack(&S);
	while(a){
		Push(&S,a%b);
		a=a/b;
	}
	while(!IsEmpty(&S)){
		printf("%d",pop(&S));
	}
}


栈的进制实例效果

输入十进制数
88888
输入要转换进制
7
初始化成功
入栈为2
栈大小1
入栈为0
栈大小2
入栈为1
栈大小3
入栈为0
栈大小4
入栈为2
栈大小5
入栈为5
栈大小6
520102栈已经为空

栈的接口测试

int main(void) {
    SqStack stack;
    InitStack(&stack);
    Push(&stack,688);
    Push(&stack,66555);
    pop(&stack);
    getTop(&stack);
    return EXIT_SUCCESS;
}


栈的接口的实例效果

初始化成功
入栈为688
栈大小1
入栈为66555
栈大小2
出站为66555
栈大小1
栈顶元素为:688

简单的栈就到这里了。。。。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值