//该程序仅用一个数组而实现两个栈的例程。
//除非数组的每一个单元都被使用
//否则你的栈例程不能有溢出声明
#include <stdio.h>
#include <stdlib.h>
#define MinStackSize (5)
typedef struct Node *dbstack; //双栈
dbstack CreatStack(int MaxElements); //构建一个大小为MAXElements的数组
void firstPush(int x, dbstack A); //头栈push
void lastPush(int x, dbstack A); //尾栈push
int firstPop(dbstack A); //头栈pop并返回元素
int lastPop(dbstack A); //尾栈pop并返回元素
void isEmpty(dbstack A); //判断元素是否为空
void isFull(dbstack A); //判断元素是否满了
struct Node
{
int first; //从数组头部开始的栈的长度
int last; //从数组尾部开始的栈的长度
int Capacity; //栈的容量,可以作为栈是否为空的依据
int *Array;
};
int main()
{
dbstack A;
return 0;
}
void firstPush(int x, dbstack A) //头栈push
{
int i;
if (A->Capacity != 0)
{
A->first = (A->first) + 1;
i = A->first;
while (i-- > 0)
{
A->Array[i] = A->Array[i - 1];
}
A->Array[0] = x;
// printf("%d\n", A->Array[0]);
A->Capacity--;
}
else
{
printf("Out of space!!!\n");
exit(0);
}
}
void lastPush(int x, dbstack A) //尾栈push
{
int i;
int lastindex; //A的最后一个元素的索引
int len; //数组的长度
len = sizeof(A) / sizeof(A[0]);
lastindex = len - 1;
if (A->Capacity != 0)
{
i = ++(A->last);
while (i++ < lastindex - 1)
A->Array[len - i] = A->Array[len - i + 1];
A->Array[lastindex] = x;
A->Capacity--;
}
else
{
printf("Out of space!!!\n");
exit(0);
}
}
int firstPop(dbstack A)
//头栈pop并返回元素
{
int firstLen = A->first;
int i;
int firstElement = A->Array[0];
if(firstLen != 0)
{
i = 0;
while(firstLen-- > 0)
{ //移动次数为长度-1
A->Array[i] = A->Array[i + 1];
i++;
}
A->Capacity++;
A->first--;
return firstElement;
}else{
printf("first stack is empty!!!\n");
exit(0);
}
}
int lastPop(dbstack A)
//尾栈pop并返回元素
{
int lastLen = A->last;
int len = sizeof(A->Array) / sizeof(A->Array[0]);
int lastNode = A->Array[len - 1]; //最后一个元素
int i;
if(A->last != 0)
{
i = len - 1;//最后一个元素的索引
while(lastLen-- > 1)
{
A->Array[i] = A->Array[i - 1];
i--;
}
(A->Capacity)++;
(A->last)--;
}else{
printf("Out of space!!!\n");
exit(0);
}
}
void isEmpty(dbstack A)//判断元素是否为空
{
if(A->first == 0 && A->last == 0)
{
printf("It is empty!!!\n");
}else{
printf("It is not empty!!!\n");
}
}
void isFull(dbstack A)//判断元素是否满了
{
if(A->Capacity == 0)
{
printf("It is full!!!\n");
}else{
printf("It is not full!!!\n");
}
}
dbstack CreatStack(int MaxElements)
//构建一个大小为MAXElements的数组
{
dbstack S;
int * Array;
if (MaxElements < MinStackSize)
{
printf("Out of space!!!\n");
exit(0);
}
S = (dbstack)malloc(sizeof(struct Node));
if (S == NULL)
{
printf("OUt of space!!!\n");
exit(0);
}
Array = (int * )malloc(sizeof(int) * MaxElements);
S->Array = Array;
S->Capacity = MaxElements;
S->first = 0;
S->last = 0;
return S;
}
void MakeEmpty(dbstack A)
{
A->first = 0;
A->last = 0;
A->Capacity = sizeof(A->Array) / sizeof(A->Array[0]);
}
一个数组实现两个栈的例程
猜你喜欢
转载自blog.csdn.net/BobDay/article/details/104793500
今日推荐
周排行