您的位置:首页 > 编程语言 > C语言/C++

栈的源代码C/C++实现

2016-03-18 23:18 429 查看
// StackFor.cpp : 定义控制台应用程序的入口点。

//visual studio 2013

//栈顺序存储表示

#include "stdafx.h"

#include "iostream"

#define MAX 23

//初始化Stack的大小

#define STACK_INIT_SIZE 10

//每次Stack容量不够的时候,增加分配的大小

#define STACK_INCREMENT 2

#define ok 1

using namespace std;

struct SqStack{

int *top;

int *base;

int stacksize;//当前已经分配的内存空间

};

//初始化Stack

int InitStack(SqStack &stack)

{

if (!(stack.base = (int*)malloc(STACK_INIT_SIZE*sizeof(int))))

{

cout << "初始化ERROR" << endl;

exit(OVERFLOW);

}

cout << "Stack初始化成功" << endl;

stack.top = stack.base;

stack.stacksize = STACK_INIT_SIZE;

return ok;

}

//销毁Stack

int DestroyStack(SqStack &stack)

{

free(stack.base);

stack.base = NULL;

stack.top = NULL;

stack.stacksize = 0;

return ok;

}

//清空栈

int ClearStack(SqStack &stack)

{

stack.base = stack.top;

return ok;

}

//看Stack是否为空

void IsEmptyStack(SqStack stack)

{

if (stack.base == stack.top)

{

cout << "Stack is empty" << endl;

}

else{

cout << "Stack is not empty" << endl;

}

}

//返回Stack的长度

int StackLength(SqStack stack)

{

return stack.top - stack.base;

}

//得到栈顶元素

int GetTopStack(SqStack stack,int &topElem)

{

if (stack.top > stack.base)

{

topElem = *(stack.top - 1);

return true;

}

return false;

}

//把元素压栈

int PushStack(SqStack &stack, int pushElemment)

{

if ((stack.top - stack.base) >= stack.stacksize)//栈满,追加空间

{

stack.base = (int*)realloc(stack.base, (stack.stacksize + STACK_INCREMENT)*sizeof(int));

if (!stack.base)

{

exit(OVERFLOW);//存储分配失败

}

stack.top = stack.base + stack.stacksize;

stack.stacksize += STACK_INCREMENT;

}

*(stack.top)++ = pushElemment;

cout << *(stack.top-1) << endl;

return ok;

}

//元素出栈

int PopStack(SqStack &stack, int &popElemment)

{

if (stack.base==stack.top)

{

return false;

}

else

{

popElemment = *--stack.top;

}

return ok;

}

int _tmain(int argc, _TCHAR* argv[])

{

SqStack stack;

int elem;

InitStack(stack);

for (int i = 0; i < MAX; i++)

{

PushStack(stack, i);

}

int stackLength = StackLength(stack);

cout << "栈的长度:" <<stackLength << endl;

GetTopStack(stack, elem);

cout << "栈顶:" << elem << endl;

cout << "栈是否为空:" << endl;

IsEmptyStack(stack);

//以下是出栈操作

int popElemment;

for (int i = 0; i < stackLength; i++)

{

PopStack(stack, popElemment);

cout << popElemment << endl;

}

int popElem;

GetTopStack(stack, popElem);

cout << "栈顶:" << popElem << endl;

cout << "栈是否为空:" << endl;

IsEmptyStack(stack);

system("pause");

return 0;

}

可能有些地方有buf,我测试了一部分,如若找出bug 请联系我,谢谢!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: