数据结构 栈

来源:互联网 发布:网络安全法的基本特点 编辑:程序博客网 时间:2024/05/21 06:20

// stack.h

#ifndef _STACK_H

#define _STACK_H

 

#include <stdio.h>

#include<stdlib.h>

#include <tchar.h>

#include <iostream>

#include <stdexcept>

#define STACK_INIT_SIZE 100

#define STACKINCREMENT 10

 

template <class elem>

class stack

{

private:

elem *top;

elem *base;

int length;

int stacksize;

public:

stack();

bool IsEmpty();

elem GetTop();

void Push(elem e);

void Pop();

int StackLength();

void DestoryStack();

};

 

template <class elem>

stack<elem>::stack()

{

base=new elem[STACK_INIT_SIZE];

*base=NULL;

if(!base) exit (1);

top=base;

length=0;

stacksize=STACK_INIT_SIZE;

}

 

template <class elem>

bool stack<elem>::IsEmpty()

{

if(top==base)

{

return true;

}

else

{

return false;

}

}

 

template <class elem>

elem stack<elem>::GetTop()

{

if(IsEmpty())

{

exit (1);

}

else

{

return *(top-1);

}

}

 

template <class elem>

void stack<elem>::Push(elem e)

{

if(top-base>=stacksize) 

{

if(!(base=(elem*)realloc(base,stacksize+STACKINCREMENT)))  exit (1);

stacksize+=STACKINCREMENT;

}

if(IsEmpty()) ++top;

*top=e;

++top;

//++length;

}

 

template <class elem>

void stack<elem>::Pop()

{

if(IsEmpty()) exit(1);

--top;

*top=NULL;

//--length;

//return *top;

}

 

template <class elem>

int stack<elem>::StackLength()

{

elem *e;

e=base;

length=0;

while((++e)!=top)

{

//++e;

++length;

}

return length;

}

 

template <class elem>

void stack<elem>::DestoryStack()

{

delete[] base;

//delete[] top;

}

 

#endif

 

// main.cpp

#include "stdafx.h"

#include "stack.h"

 

using namespace std;

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

{

cout<<"let enter stack world!"<<'/n';

cout<<"New stack"<<'/n';

stack<int> T;

for(int i=1;i<10;++i)

{

T.Push(i);

cout<<T.GetTop()<<'/t';

}

cout<<'/n'<<"This stack length is"<<'/t'<<T.StackLength()<<'/n';

cout<<"Let pop the top"<<'/n';

for(int j=1;j<10;j++)

{

cout<<T.GetTop()<<'/t';

T.Pop();

}

cout<<'/n'<<"This stack length is"<<'/t'<<T.StackLength()<<'/n';

T.DestoryStack();

system("pause");

return 0;

}

原创粉丝点击