#include <stdio.h>
#define max 20
/*通常用一维数组来实现堆栈*/
typedef struct SNode* stack;/*stack->stack*/
struct SNode {
int data[max];
int top;/*下标,就是最后一个数,不是指向它后面的空位置*/
};
/*建立空栈*/
stack make_empty_stack(void)
{
stack ptrs = malloc(sizeof(struct SNode));
ptrs->top = -1;
return ptrs;
}
/*入栈*/
void push(stack ptrs, int item)
{
if (ptrs->top == max - 1)
{
printf("满了\n");
return;
}
else
{
ptrs->data[++ptrs->top] = item;
return;
}
}
/*出栈*/
int pop(stack ptrs)
{
if (ptrs->top < 0)
{
printf("栈空\n");
return;
}
else
{
int s = ptrs->data[ptrs->top--];
return s;
}
}
/*用一维数组实现2个堆栈,即从两头相向出发*/
struct Double_stack {
int data[max];
int top1;
int top2;
};
typedef struct Double_stack* dstack;
/*建立空栈*/
dstack make_empty_double_stack(void)
{
dstack ptrs = malloc(sizeof(struct Double_stack));
ptrs->top1 = -1;
ptrs->top2 = max;
}
/*入栈操作*/
void push_dstack(dstack ptrs, int item,int tag)
{
if ((ptrs->top2 - ptrs->top1) == 1)//不是0,是1,要注意
{
printf("栈满\n");
return;
}
else if (tag == 1)
{
ptrs->data[++ptrs->top1] = item;
return;
}
else if (tag == 2)
{
ptrs->data[--ptrs->top2] = item;
return;
}
}
/*出栈操作*/
int pop_dstack(dstack ptrs, int tag)
{
if (tag == 1)
{
if (ptrs->top1 == -1)
{
printf("栈空\n");
return NULL;
}
else
{
int p = ptrs->data[ptrs->top1--];
return p;
}
}
else
{
if (ptrs->top2 = 20)
{
printf("栈空\n");
return NULL;
}
else
{
int p = ptrs->data[ptrs->top2++];
return p;
}
}
}
三、堆栈的一般(数组)实现
最新推荐文章于 2024-07-25 15:58:50 发布