数据结构---栈的两种实现
第一种
#include<iostream>
#include<malloc.h>
#include<assert.h>
#define STACK_LEN 10
using namespace std;
typedef struct stack
{
int *top;
int *base;
int alloclength;
}Stack;
void StackNew(Stack *s);
void StackDispose(Stack *s);
void StackPush(Stack *s,int vlaue);
int StackPop(Stack *s);
Stack s;
int main()
{
StackNew(&s);
std::cout<<"Stack in:";
for(int i=0;i<s.alloclength;i++)
{
std::cout<<i<<" ";
StackPush(&s,i);
}
std::cout<<endl<<"Stack out:";
for(int i=0;i<s.alloclength;i++)
{
std::cout<<StackPop(&s)<<" ";
}
StackDispose(&s);
getchar();
return 0;
}
void StackNew(Stack *s)
{
s->alloclength=STACK_LEN;
s->base=(int *)malloc(STACK_LEN*sizeof(int));
s->top=s->base;
assert(s->base!=NULL);
}
void StackDispose(Stack *s)
{
while(s->top!=s->base)
{
free(s->top--);
}
std::cout<<endl<<"dispose finished";
}
void StackPush(Stack *s,int i)
{
*(s->top++)=i;
}
int StackPop(Stack *s)
{
return *(--s->top);
}
结果:
第二种
#include<iostream>
#include<malloc.h>
#include<assert.h>
#define STACK_LEN 20
using namespace std;
typedef struct stack
{
int *elem;
int logiclength;
int alloclength;
}Stack;
void StackNew(Stack *s);
void StackDispose(Stack *s);
void StackPush(Stack *s,int vlaue);
int StackPop(Stack *s);
Stack s;
int main()
{
StackNew(&s);
std::cout<<"Stack in:";
for(int i=0;i<s.alloclength;i++)
{
std::cout<<i<<" ";
StackPush(&s,i);
}
std::cout<<endl<<"Stack out:";
for(int i=0;i<s.alloclength;i++)
{
std::cout<<StackPop(&s)<<" ";
}
StackDispose(&s);
getchar();
return 0;
}
void StackNew(Stack *s)
{
s->logiclength=0;
s->alloclength=STACK_LEN;
s->elem=(int *)malloc(STACK_LEN*sizeof(int));
assert(s->elem!=NULL);
}
void StackDispose(Stack *s)
{
while(s->logiclength!=0)
{
free(&s->elem[s->logiclength--]);
}
std::cout<<endl<<"dispose finished";
}
void StackPush(Stack *s,int i)
{
s->elem[s->logiclength++]=i;
}
int StackPop(Stack *s)
{
return s->elem[-- s->logiclength];
}
结果