学习到数据结构栈的部分,一下是关于C语言实现栈的顺序存储结构的代码实现,并用二进制转十进制,二进制转八进制两个例子进行测试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef char ElemType;//栈存储的元素类型
#define STACK_INCREMENT_LENGTH 10 //栈的增长长度
typedef struct node
{
ElemType *top; //栈顶
ElemType *bottom; //栈底
int max_length; //栈的最大容量
}SqStack;
int initStack(SqStack &s, int n) //初始化一个栈,栈的容量为n
{
s.bottom = (ElemType *)malloc(n*sizeof(SqStack)); //初始化内存空间
if(!s.bottom) //内存分配失败
return 0;
s.top = s.bottom;
s.max_length = n;
return 1;
}
int push(SqStack &s, ElemType e)
{
if(s.top - s.bottom >= s.max_length)//栈满
{
s.bottom = (ElemType *)realloc(s.bottom, (s.max_length + STACK_INCREMENT_LENGTH)*sizeof(ElemType));
if(!s.bottom) //分配内存失败
return 0;
s.top = s.bottom + s.max_length;
s.max_length = s.max_length + STACK_INCREMENT_LENGTH;
}
*s.top = e;
s.top++;
return 1;
}
int pop(SqStack &s, ElemType &e)//出栈的元素保存在变量e中
{
if(s.bottom == s.top)//栈空
return 0;
e = *(--s.top);
return 1;
}
void clearStack(SqStack &s) //清空栈
{
s.top = s.bottom;
}
void destroyStack(SqStack &s) //摧毁栈
{
int i, len;
len = s.max_length;
for(i=0; i < len; i++)
{
free(s.bottom);
s.bottom++;
}
s.bottom = s.top = NULL;
s.max_length = 0;
}
int getN(SqStack &s)
{
return s.top-s.bottom;
}
int main()
{
/*二进制转十进制*/
/*
SqStack s;
initStack(s,100);
printf("请输入二进制数,以'#'结束输入:\n");
char c;
scanf("%c", &c);
while( c != '#')
{
push(s, c);
scanf("%c", &c);
}
getchar();//接收换行'\n'
int i,len = getN(s);
int sum = 0;
printf("二进制数的位数为:%d\n", len);
for(i = 0; i < len; i++)
{
pop(s, c);
sum += (c - '0')*pow(2.0, i);
}
printf("十进制数为:%d\n", sum);
*/
/*二进制转八进制*/
/*
SqStack s1, s2;
initStack(s1, 100);//存储二进制数
initStack(s2, 100);//存储八进制数
char c;
printf("请输入二进制数,以'#'结束输入:\n");
scanf("%c", &c);
while( c != '#')
{
push(s1, c);
scanf("%c", &c);
}
getchar();
int i,j,sum = 0;
int n = getN(s1)/3;
for(i=0; i <= n; i++)
{
for(j = 0; j < 3; j++)
{
if(!pop(s1, c))//栈空时
c = '0';
sum += (c - '0')*pow(2.0, j);
}
push(s2, (char)(sum+'0'));
sum = 0;//归零
}
printf("八进制为:\n");
int len = getN(s2);
for(i=0; i < len; i++)
{
pop(s2, c);
printf("%c", c);
}
printf("\n");
*/
return 0;
}