MOOC 2.2 堆栈

1. 顺序存储

#include <cstdio>
#define MaxSize <存储元素的最大个数> 
typedef struct SNode *Stack;
struct SNode
{
	ElementType Data[MaxSize];
	int Top;
};

// 1. 入栈
void Push(Stack PtrS, ElementType item)
{
	if(PtrS->Top == MaxSize - 1)
	{
		printf("堆栈满");
		return ;
	}
	else
	{
		PtrS->Data[++(PtrS->Top)] = item;
		return ;
	}
} 

// 2. 出栈
ElementType Pop(Stack PtrS)
{
	if(PtrS->Top == -1)
	{
		printf("堆栈空");
		return ERROR; 
	}
	else
	{
		return (PtrS->Data[(PtrS->Top)--]);
	}
} 

  

共享栈

// 共享栈
#define MaxSize <存储元素的最大个数>
struct DStack
{
	ElementType Data[MaxSize];
	int Top1;
	int Top2;
}S;

S.Top1 = -1;
S.Top2 = MaxSize;

void Push(struct DStack *PtrS, ElementType item, int Tag)
{
	if(PtrS->Top1 + 1 == PtrS->Top2)
	{
		printf("堆栈满");
		return ; 
	}
	if(Tag == 1)
		PtrS->Data[++(PtrS->Top1)] = item;
	else
		PtrS->Data[--(PtrS->Top2)] = item;
	return ;
}

ElementType Pop(struct DStack *PtrS, int Tag)
{
	// Tag作为区分两个堆栈的标志, 取值为1和2 
	if(Tag == 1)
	{
		if(PtrS->Top1 == -1)
		{
			printf("堆栈1空");
			return NULL; 
		}
		else
		{
			return PtrS->Data[(PtrS->Top1)--];
		}
	}
	else
	{
		if(PtrS->Top2 == MaxSize)
		{
			printf("堆栈2空");
			return NULL; 
		}
		else
		{
			return PtrS->Data[(PtrS->Top2)++];
		}
	}
}

  

3. 链式栈

// 堆栈的链式存储
typedef struct SNode *Stack;
struct SNode
{
	ElementType Data;
	struct SNode *Next;
};
// 栈顶指针top应该在链表的头部

// 1. 初始化堆栈(建立空栈) 
Stack CreateStack()
{
	Stack S;
	S = (Stack)malloc(sizeof(struct SNode));
	S->Next = NULL;
	return S;
} 

// 判断堆栈是否为空
int IsEmpty(Stack S)
{
	return (S->Next == NULL);
}

// 插入结点
void Push(ElementType item, Stack S)
{
	struct SNode *TmpCell;
	TmpCell = (struct SNode *)malloc(sizeof(struct SNode));
	TmpCell->Data = item;
	TmpCell->Next = S->Next;
	S->Next = TmpCell;
} 

// 删除结点
ElementType Pop(Stack S)
{
	struct SNode *FirstCell;
	ElementType TopElem;
	if(IsEmpty(S))
	{
		printf("堆栈空");
		return NULL; 
	}
	else
	{
		FirstCell = S->Next;
		S->Next = FirstCell->Next;
		TopElem = FirstCell->Data;
		free(FirstCell);
		return TopElem;
	}
} 

  

原文地址:https://www.cnblogs.com/mjn1/p/11441604.html