堆栈的基本操作集合

堆栈是类似于容器的一种数据结构,先进到容器的最后出容器。

一 顺序栈的存储结构

typedef  int Position;
typedef  struct SNode  *PtrToSNode;
struct SNode {
	ElementType *Data;
	Position Top;
	int Maxsize;
};
typedef  PtrToSNoSNode  Stack;

顺序栈 堆栈的创建

Stack  CreateStack  (int MaxSize)
{
	Stack S;
	S=(Stack)malloc(sizeof(struct SNode));
	S->Data=(ElementType*)malloc(MaxSize*sizeof(ElementType));
	S->Top=-1;
	S->Maxsize=Maxsize;
	return S;
}

顺序栈的入栈操作

bool Push(Stack S,ElementType  X)
{
	if(S->Top+1==S->Maxsize) 
	{
		printf("堆栈满了\n");
		return false;
	}
	else {
		S->Data[++(S->Top)]=X;
		return true;
	}
}

顺序栈的出栈操作

ElementType Pop(Stack S)
{
	if(S->Top==-1) 
	{
		printf("堆栈是空的\n");
		return -1;  //返回一个堆栈中不可能的值,作为错误的信号;
	}
	else {
		return S->Data[(S->Top)--];
	}

二 堆栈的链式操作

存储结构

Stack  CreateStack  ()(带头结点)
{
	Stack  S;
	S=(Stack)malloc(sizeof(struct SNode));
	S->Next=NULL;
	return S;
}

入栈操作(只可以在头操作,不用考虑栈是否满)

bool Push(Stack S,ElementType  X)
{
	Stack  temp;
	temp=(Stack) malloc(sizeof(struct SNode));
	temp->Next=NULL;
	temp->Data=X;
	temp->Next=S->Next;
	S->Next=temp;
	return true;
}

出栈操作

ElementType Pop(Stack S)
{
	ElementType  num;
	Stack  temp;
	if(!S->Next) 
	{
		printf("堆栈是空的\n");
		return -1;
	}
	else {
		 temp= S->Next;
		 num=temp->Data;
		 S->Next=temp->Next;
		 free(temp);
	      return   num;  //注意返回的数字一定要先临时放到一个存储单元,因为他原来的存储单元被free;
	}
}

版权声明:本文为mask1010原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。