チェーンスタックの基本操作はc++を実現する
2237 ワード
注意:エラーや補足が必要な場合は、初心者の方にお知らせください.ありがとうございます.
#include
#include
#include
#include
#include
#include
#include
using namespace std;
/* */
typedef struct node
{
int data;
struct node *next;
}stacknode;
/* */
typedef struct linkstack
{
stacknode *base;
stacknode *top;
}linkstack;
/* */
linkstack *init_stack()
{
linkstack *s;
s=(linkstack*)malloc(sizeof(linkstack));
s->base=(stacknode*)malloc(sizeof(stacknode));
s->top=s->base;
s->base->next=NULL;
return s;
}
/* */
bool is_empty_linkstack(linkstack s)
{
if(s.base==s.top)
{
return true;
}
else
{
return false;
}
}
/* */
void push(linkstack *s,int e)
{
stacknode *p;
p=(stacknode*)malloc(sizeof(stacknode));
p->data=e;
p->next=s->top;
s->top=p;
}
/* */
void pop(linkstack *s,int &e)
{
if(is_empty_linkstack(*s))
{
printf(" ");
}
else
{
stacknode *p=s->top;
e=p->data;
s->top=p->next;
free(p);
}
}
/* */
void delete_stack(linkstack *s)
{
stacknode *p;
while(!is_empty_linkstack(*s))
{
p=s->top;
s->top=p->next;
free(p);
}
printf("
");
}
/* */
int length(linkstack s)
{
stacknode *p=s.top;
int i=0;
while(p!=s.base)
{
i++;
p=p->next;
}
return i;
}
/* */
void get_top(linkstack s,int &e)
{
if(is_empty_linkstack(s))
{
printf(" ");
}
else
{
e=s.top->data;
}
}
int main()
{
linkstack *s;
int l,e;
s=init_stack();
printf(" :");
scanf("%d",&l);
printf(" :");
for(;l>0;l--)
{
scanf("%d",&e);
push(s,e);
}
printf(" :");
while(!is_empty_linkstack(*s))
{
pop(s,e);
printf("%d",e);
}
printf("
");
delete_stack(s);
return 0;
}