更新一些堆栈的操作实现

堆栈的实现包括有使用指针的实现方式和使用数组的实现方式。

下面为指针的实现方式:

//堆栈也叫做LIFO结构
/* 堆栈的基本操作包括清空栈和判断是否是空栈都是栈的操作的一部分
 *栈顶是唯一可见的操作
 *栈的本质其实也是一个表,任何表的方法都可以用来实现栈
 *栈的实现包括两种流行的方法,一种是使用指针来实现,另一种是使用数组来实现
*/

//栈的链表实现
//1.使用单链表来实现
//首先是定义:

#ifdef _Stack_h
struct Node
typedef struct Node *PtrToNode;
typedef ProToNode Stack;

int
IsEmpty(Stack S);
Stack 
CreatStack(void);
void
DisposeStack(Stack S);
void 
MakeEmpty(Stack S);
void
Push(ElementType X, Stack S);
ElementType
Top(Stack S)
void
Pop(Stack S);

#endif

struct Node
{
	ElementType Element;
	PtrToNode Next;
};

//测试堆栈是否为空
int 
IsEmpty(Stack S)
{
	return S->Next == NULL
}
Stack
CreatStack(void)
{
	Stack S;
	
	S = malloc(sizeof(struct Node));
	if(S == NULL)
		FatalError("Out of space");
	S->Next == NULL;
	MakeEmpty(S)
	return S;
}
void	//创建一个空的栈 
MakeEmpty(Stack S)
{
	if(S == NULL)
		Error("must use CreastStack first");
	else
		while(!IsEmpty(S))
			pop(S);
	
}
void	//实现压栈的操作
Push(ElementType  X,Stack S)
{
	PtrToNode TmpCell;
	
	TmpCell = malloc(sizeof(struct Node));
	if(TmpCell == NULL)
		FatalError("Out of space");
	else
	{
		TmpCell -> ElementType = X;
		TmpCell -> Next = S->Next;
		S->Next = TmpCell;
	}
}
ElementType
Top(Stack S)
{
	if(!IsEmpty(S))
		return S->next->Element;
	Error("Empty Stack");
	return 0;  //return value is used to avoid waring
}
void
pop(Stack S)
{
	PtrToNode FirstCell;
	
	if(IsEmpty(S))
		Error("Empty Stack");
	else
	{
		FirstCell = S->next;
		S->Next = S->Next->Next;
		free(FirstCell);
	}
}

下面是使用数组的实现方式:

#ifdef _Stack_h
struct Stackrecord;
struct StackRecord *Stack;
int IsEmpty(Stack S);
int IsFull(Stack S);
Stack CreatStack(int MaxElement);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
ElementType Top(Stack S);
void Pop(Stack S);
ElementType TopAndPop(Stack S);
#endif /*Stack.h*/

Stack CreatStack(int MaxElement)
{
	Stack S;
	
	if(MaxElement<MinStackSize)
			Error("Stack is too small");
	S = malloc(sizeof(struct StackRecord));
	if(S ==NULL)
		FatalError("Out of space");
	S->Array = malloc(sizeof(ElementType)*MaxElement);
	if(S->Array == NULL)
		FatualError("Out of space");
	S->Capacity = MaxElement;
	MakeEmpty(5);
	
	return s;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值