c语言:顺序栈的实现

#include<iostream>
#include<stdio.h>
#include<math.h>
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
using namespace std;
typedef struct Stack  //结构体定义
{  
	int *elem;          //数据域
	int top;    //顺序栈栈顶
	int stacksize;     //顺序栈当前长度
}Stack;
//函数声明部分
void Error(char *s);     //错误处理函数
Stack Creat_Stack();//若干个元素的顺序栈
void Destroy_Stack(Stack & l); //销毁顺序栈	
void Clear_Stack(Stack & l);   //清空顺序栈
int Getlength_Stack(Stack &l); //计算顺序栈长度
void Gettop_Stack(Stack &l, int e);  //得到顺序栈栈顶元素
void Push_Stack(Stack &L, int e);  //压栈操作函数
void Pop_Stack(Stack &L, int e);   //出栈操作函数
void Increment_Stack(Stack & l);   //增加顺序栈空间函数
void Print_Stack(Stack & l);       //输出顺序栈元素函数
//函数实现部分
void Error(char *s)
{
	cout << s << endl;
	exit(1);
}

Stack Creat_Stack()
{
	int length = 0;
	int data = 0;
	Stack l;
	l.elem = new int[STACK_INIT_SIZE];
	if (!l.elem)
		Error("内存申请失败!");
	l.top = -1;
	l.stacksize = STACK_INIT_SIZE;
	cout << "请输入顺序栈长度:";
	cin >> length;
	cout << "请输入顺序栈元素内容:" << endl;
	for (int i = 0; i < length; i++)
	{
		cin >> data;
		l.elem[i] = data; //这一步是重点
		l.top++;
	}
	cout << "顺序栈创建成功!" << endl;
	return l;
}
void Destroy_Stack(Stack &l)
{
	delete[] l.elem;
	l.top = -1;
	l.stacksize = 0;
	cout << "该顺序栈销毁成功!" << endl;
}
void Clear_Stack(Stack &l)
{
	l.top = -1;
}

int Getlength_Stack(Stack & l)
{
	return (l.top + 1);
}
void Gettop_Stack(Stack &l, int e)
{
	if (l.top == -1)
		Error("该栈为空栈!");
	e = l.elem[l.top];
	cout << "该顺序栈的栈顶元素是:";
	cout << e << endl;
}
void Increment_Stack(Stack &l)
{
	int *newstack = new int[l.stacksize + STACK_INCREMENT];
	if (!newstack)
		Error("存储分配失败!");
	for (int i = 0; i < l.top; i++)
	{
		newstack[i] = l.elem[i];
	}
	l.elem = newstack;
	delete[] l.elem;
	l.stacksize += STACK_INCREMENT;
}
void Push_Stack(Stack &l, int e)
{
	if (l.top == (l.stacksize - 1))
		Increment_Stack(l);
	l.elem[++l.top] = e;
}
void Pop_Stack(Stack &l, int e)
{
	if (l.top == -1)
		Error("该顺序栈为空栈!");
	e = l.elem[l.top--];
	cout << e << endl;
}
void Print_Stack(Stack &l)
{
	cout << "该顺序栈的元素是:" << endl;
	for (int i = l.top; i > -1; i--)
	{
		cout << l.elem[i] << " ";
	}
	cout << endl;
}

int main()
{
	Stack s;
	int d = 0;
	int t = 0;
	int q = 0;
	s = Creat_Stack();
	cout << "该顺序栈的长度是:" << Getlength_Stack(s) << endl;
	Print_Stack(s);
	Gettop_Stack(s, d);
	cout << "请输入要入栈的元素:";
	cin >> t;
	Push_Stack(s, t);
	cout << "该顺序栈的长度是:" << Getlength_Stack(s) << endl;
	Print_Stack(s);
	cout << "出栈的元素是:";
	Pop_Stack(s, q);
	Destroy_Stack(s);
	return 0;
}

你可能感兴趣的:(数据结构,编程语言,C语言,栈)