上一个
下一个

栈(2)——顺序栈

1.全部代码

				
					#include <iostream>
#include <cstdlib>
using namespace std;

class SeqStack{
private:
	int *base;
	int *top;
	int size;

public:
	int length;
	//base指向index:0
	//top指向空的length,实际有元素的是length-1
	SeqStack()
	{
		size=0;
		length=0;
	}
	bool InitStack(int n)
	{
		base=(int *)malloc(n*sizeof(int));
		if(base==nullptr)
		{
			cout<<"初始化分配内存出错啦!"<<endl;
			return false;
		}
		size=n;
		length=0;
		top=base;
		return true;
	}
	bool DestroyStack()
	{
		if(base!=nullptr)
		{
			free(base);
			base=nullptr;
		}
		top=nullptr;
		size=0;
		length=0;
		return true;
	}
	bool ClearStack()
	{
		top=base;
		return true;
	}
	bool IsEmpty()
	{
		return top==base;
	}
	int GetTop()
	{
		if(IsEmpty())
			return -1;
		else{
			return *(top-1);
		}
	}
	bool push(int e)
	{
		if(length==size)
		{
			base=(int *)realloc(base,2*size*sizeof(int));
			if(base==nullptr)
			{
				cout<<"初始化分配内存出错啦!"<<endl;
				return false;
			}
			size*=2;
		}
		length++;
		*top=e;
		top++;
		return true;
	}
	int pop()
	{
		if(IsEmpty())
			return -1;
		else
		{
			length--;
			return *(--top);
		}
		
	}
	int GetLength()
	{
		return length;
	}
};
int main()
{
	SeqStack a;
	a.InitStack(10);
	for(int i=0;i<15;i++)
		a.push(i);
	while(!a.IsEmpty())
	{
		cout<<a.pop()<<endl;
		cout<<"leng:"<<a.GetLength()<<endl;
		
	}
}





				
			
订阅评论
提醒
0 评论
内联反馈
查看所有评论

《栈(2)——顺序栈》

0
希望看到您的想法,请您发表评论x