标签:转换 进制 SqStack ElemType void --- base return top
说明1:以下代码在VS2017中编译通过,读者使用时可以直接将头文件(SqStack.h),源文件(SqStack.c),主文件(main.c)中的内容直接拷贝过去,即可编译运行!
说明2:图示
头文件:SqStack.h(函数的声明)
#ifndef _SQSTACK_H_
#define _SQSTACK_H_
#include <stdio.h>
#include <malloc.h>
#include <assert.h>
#include <stdbool.h>
#define STACK_INIT_SIZE 8
#define STACK_INCREMENT 3
#define sign //括号匹配 + 行编辑程序
#ifdef sign
#define ElemType char
#else
#define ElemType int
#endif // sign
typedef struct SqStack
{
ElemType* base;
ElemType top;
int capacity;
}SqStack;
void InitStack(SqStack* s);
void push(SqStack* s, ElemType data);
void pop(SqStack* s);
bool IsFull(SqStack* s);
bool IsEmpty(SqStack* s);
void GetTop(SqStack* s, ElemType* e);
void show(SqStack* s);
int length(SqStack* s);
void clear(SqStack* s);
void destroy(SqStack* s);
bool Increment(SqStack* s);
void Print(SqStack* s);
#endif // ! _SQSTACK_H_
源文件:SqStack.c(函数的定义)
#include "SqStack.h"
void InitStack(SqStack* s)
{
s->base = (ElemType*)malloc(sizeof(ElemType) * STACK_INIT_SIZE);
assert(s->base != NULL);
s->top = 0; //栈顶指针初始化为0
s->capacity = STACK_INIT_SIZE;
}
bool Increment(SqStack * s)
{
ElemType* NewBase = (ElemType*)realloc(s->base, sizeof(ElemType) * (s->capacity + STACK_INCREMENT));
if (NewBase == NULL)
{
printf("追加栈空间失败!\n");
return false;
}
s->base = NewBase;
s->top = 0 + s->capacity;
s->capacity += STACK_INCREMENT;
return true;
}
void Print(SqStack * s)
{
for (int i = 0; i <= s->top - 1; i++)
printf("%c", s->base[i]);
printf("\n");
}
void push(SqStack* s, ElemType data)
{
if (IsFull(s) && !Increment(s))
{
printf("栈空间已满,无法入栈!\n");
return;
}
s->base[s->top++] = data;
}
void pop(SqStack* s)
{
if (IsEmpty(s))
{
printf("栈空,无法出栈!\n");
return;
}
s->top--;
}
bool IsFull(SqStack* s)
{
return s->top == s->capacity;
}
bool IsEmpty(SqStack* s)
{
return s->top == 0;
}
void GetTop(SqStack* s, ElemType* e)
{
if (IsEmpty(s))
{
printf("栈空,无法获取栈顶元素!\n");
return;
}
*e = s->base[s->top - 1];
}
//栈的遍历
void show(SqStack* s)
{
for (int i = s->top - 1; i >= 0; i--)
printf("%d", s->base[i]);
}
int length(SqStack* s)
{
return s->top;
}
void clear(SqStack* s)
{
s->top = 0;
}
void destroy(SqStack* s)
{
free(s->base);
s->base = NULL;
s->capacity = s->top = 0;
}
主文件:main.c(测试文件)
#include "SqStack.h"
//进制转换
void convert_2(value)
{
SqStack S;
InitStack(&S);
while (value != 0)
{
push(&S, value % 2); //余数入栈
value /= 2; //商数
}
ElemType e;
while (!IsEmpty(&S))
{
GetTop(&S,&e);
printf("%d", e);
pop(&S);
}
}
int main()
{
int value = 9132;
convert_2(value);
return 0;
}
标签:转换,进制,SqStack,ElemType,void,---,base,return,top 来源: https://blog.csdn.net/TianYanRen111/article/details/110095814
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。