栈------顺序存储

栈:

代码实现:

#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<stdio.h>
using namespace std;

//栈的结构定义
#define MAXSIZE 100
typedef int SElemType;
typedef struct SqStack
{
	SElemType data[MAXSIZE];
	int top;
}SqStack;

//初始化空栈
void initStack(SqStack &s)
{
	s.top = 0;
}

//判断栈空
bool isEmpty(SqStack s)
{
	if (s.top == 0)
	{
		printf("空栈\n");
		return true;
	}
	else
	{
		return false;
	}
}

//栈满
bool isFull(SqStack s)
{
	if (s.top == MAXSIZE)
	{
		return true;
	}
	else
	{
		return false;
	}
}

//取栈顶元素
void getTopElem(SqStack s, SElemType &e)
{
	if (!isEmpty(s))
		e = s.data[s.top - 1];
	else
		printf("空栈 ,取栈顶失败\n");
}

//入栈
void push(SqStack &s, SElemType e)
{
	if (!isFull(s))
	{
		s.data[s.top] = e;
		s.top++;
	}
	else
	{
		printf("此栈已满,入栈失败\n");
	}
}

//出栈
void pop(SqStack &s, SElemType &e)
{
	if (!isEmpty(s))
	{
		e = s.data[s.top - 1];
		s.top--;
	}
	else
	{
		printf("此栈为空,出栈失败\n");
	}
}

//利用入栈创建栈
void createSqlist(SqStack &s, int n)
{
	printf("依次输入栈内元素:\n");
	for (int i = 0; i < n; i++)
	{
		SElemType e;
		scanf("%d", &e);
		push(s, e);
		getchar();//吸入回车符
	}
}

//打印输出栈内元素
void printStack(SqStack s) {
	int stackLen = s.top;//栈长
	printf("打印栈内元素:");
	for (int i = stackLen-1; i >= 0;  i--) {
		printf("%d ", s.data[i]);
	}
	printf("\n");
}

void main()
{
	SqStack s;
	initStack(s);

	createSqlist(s, 5);//产生一个从栈顶到栈底为:a,c,e,g,i的栈
	printStack(s);

	//入栈新元素:j
	printf("输入一个新元素入栈(如2):");
	SElemType pushElem;
	scanf("%d", &pushElem);
	push(s, pushElem);
	printStack(s);

	//出栈
	SElemType popElem;
	pop(s, popElem);
	printf("\n出栈元素为%d\n", popElem);
	printStack(s);

	system("pause");
}

参考资料:

《大话数据结构》

大神博客:https://blog.csdn.net/u010366748/article/details/50639195

猜你喜欢

转载自blog.csdn.net/qq_39503189/article/details/81433190