栈:
栈先进后出,队列先进先出
创建栈:
#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;
#define MAX 1024
typedef struct stack
{
ElementType data[MAX];
int top;
}Stack;
Stack *CreateStack(void)
{
Stack *s=(Stack*)malloc(sizeof(Stack));
s->top=-1;
return s;
}
int StackEmpty(Stack *s)
{
if(s)
{
if(s->top==-1)
return 1;
else
return 0;
}
return -1;
}
int StackFull(Stack *s)
{
if(s)
{
if(s->top==MAX-1)
return 1;
else
return 0;
}
else
return -1;
}
void Push(Stack *s,ElementType x)
{
if(s)
{
if(StackFull(s)==0)
s->data[++s->top]=x;
}
else
return ;
}
ElementType Pop(Stack *s)
{
if(s)
{
if(StackEmpty(s)==0)
return s->data[s->top--];
}
else
return -1;
}
void ClearStack(Stack *s)
{
if(s)
s->top=-1;
}//清除栈里面的内容;
void DestroySack(Stack *s)
{
if(s)
{
s->top=-1;
free(s);
s=NULL;
}
}//把整个栈都清除;
int main(int argc,char *argv[])
{
Stack *s=CreateStack();
ElementType x;
while(1)
{
scanf("%d",&x);
if(x==0)
break;
push(s,x);
}//入栈
while(StackEmpty(s)==0)
{
x=Pop(s);
printf("%d\t",x);
}//出栈打印
DestroySack(s); //调用函数清除栈
return 0;
}
用栈做计算器转换进制:
#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;
#define MAX 1024
typedef struct stack
{
ElementType data[MAX];
int top;//栈顶
}Stack;
Stack * CreateStack(void)
{
Stack *s = (Stack *)malloc(sizeof(Stack));
s->top = -1;
return s;
}
int StackEmpty(Stack *s)
{
if(s->top == -1)
return 1;
else
return 0;
}
int StackFull(Stack *s)
{
if(s->top == MAX - 1)
return 1;
else
return 0;
}
void Push(Stack *s,ElementType x)
{
if(StackFull(s) == 0)
{
s->data[++s->top] = x;// ++s->top; s->data[s->top] = x;
}
}
ElementType Pop(Stack *s)
{
if(StackEmpty(s) == 0)
return s->data[s->top--];
}
/*void ClearStack(stack *s)
{
s->top=-1;
}
void destory(stack *s)
{
s->top=-1;
free(stack);
stack=NULL;
}*/
int main(int argc,char *argv[])
{
Stack *s = CreateStack();
ElementType x;
ElementType r;
scanf("%d",&x);
scanf("%d",&r);
ElementType a;
while(1)
{
a=x%r;
x=x/r;
Push(s,a);
if(x==0)
break;
}
while(StackEmpty(s) == 0)
{
if(r==16)
{
x = Pop(s);
if(x>=10)
{
x='A'+x-10;
printf("%c\t",x);
}
else
{
printf("%d ",x);
}
}
else
{
x = Pop(s);
printf("%d\t",x);
}
}
//destory(stack);
printf("\n");
return 0;
}