用数组去模拟栈

用数据模拟栈,在一定的程度上提高了效率。但浪费了一些空间。下面我附上代码:

#include <stdlib.h>
#include <stdio.h>

#define EmptyTOS (-1)
#define MinStackSize (5)
struct StackRecord;
typedef struct StackRecord *Stack;
struct StackRecord
{
	int Capacity;
	int TopOfStack;
	int *Array;
};

/*
 * 创建一个stack
 */
Stack CreateStack(int MaxElements)
{
	Stack S;
	
	if (MaxElements < MinStackSize)
	{
		printf("Stack size is too small.\n");
	}

	S = (Stack)malloc(sizeof(struct StackRecord));
	if (S == NULL)
	{
		printf("out of space!!!\n");
	}

	S->Array = (int *)malloc(sizeof(int)*MaxElements);
	if (S->Array == NULL)
	{
		printf("out of space !!!\n");
	}

	S->TopOfStack = -1;
	S->Capacity = MaxElements;
//	printf("TopOfStack`s value = %d, S->Capacity = %d\n", S->TopOfStack, S->Capacity);
	return S;
}

/*
 * 释放栈
 */
void DisposeStack(Stack S)
{
	if (S != NULL)
	{
		free(S->Array);
		free(S);
	}
}
/*
 * 栈是否为空
 */
int IsEmpty(Stack S)
{
	return S->TopOfStack == EmptyTOS;
}

/*
 * 清空栈。
 */
void MakeEmpty(Stack S)
{
	S->TopOfStack = EmptyTOS;
}
/*
 * 判断栈是否满
 */
int IsFull(Stack S)
{
	if (S->TopOfStack >= S->Capacity)
	{
		return -1;
	}
	else
		return 0;
		
}

/*
 * push data.
 */
void Push(int X, Stack S)
{
	if (IsFull(S))
		printf("Full Stack\n");
	else
	{
		S->TopOfStack++;
		S->Array[S->TopOfStack] = X;
	}
}

/*
 * print stack.
 */
void ShowStack(Stack S)
{
	int i;
	printf("Now we can print the stack.\n");
	for (i = 0; i <= S->TopOfStack; i++)
	{
		if (i < S->TopOfStack)
		{
			printf("%d, ", S->Array[i]);			
		}
		else
		{
			printf("%d \n", S->Array[i]);
		}

	}
}
/*
 * 弹出第一个数.
 */
int Top(Stack S)
{
	if (IsEmpty(S))
	{
		return 0;		
	}
	else
	{
		return S->Array[S->TopOfStack];
	}
}
/*
 * pop data.
 */
int Pop(Stack S)
{
	if (IsEmpty(S))
	{
		printf("Empty Stack\n");
		return 0;		
	}
	else
	{
		S->TopOfStack --;		
	}
}

int main(void)
{
	Stack Stack1;
	Stack1 = CreateStack(10);
	Push(2, Stack1);
	Push(3, Stack1);
	Push(4, Stack1);
	Push(5, Stack1);
	Pop(Stack1);
	ShowStack(Stack1);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_807315755

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值