求数据结构 栈和队列的基本操作的编程

2024-12-17 14:03:39
推荐回答(1个)
回答1:

顺序栈代码如下
#pragma once
template
class SqStack
{
public:
SqStack(int m);
~SqStack();
void Clear();
bool IsEmpty()const;
int Length()const;
T& Top()const;
void Push(const T& e);
void Pop();
private:
T* m_base;
int m_top;
int m_size;
};

template
SqStack::SqStack(int m)
{
m_top=0;
m_base=new T[m];
m_size=m;
}
template
SqStack::~SqStack()
{
if(m_base!=NULL)
delete[] m_base;
}
template
void SqStack::Clear()
{
m_top=0;
}
template
bool SqStack::IsEmpty()const
{
return m_top==0;
}
template
int SqStack::Length()const
{
return m_top;
}
template
T& SqStack::Top()const
{
return m_base[m_top-1];
}
template
void SqStack::Push(const T& e)
{
if(m_top>=m_size)
{
T* newbase;
newbase=new T[m_size+10];
for(int j=0;j newbase[j]=m_base[j];
delete[] m_base;
m_base=newbase;
m_size+=10;
}
m_base[m_top++]=e;
}
template
void SqStack::Pop()
{
m_top--;
}

#include
#include"SqStack.h"

using namespace std;

int main()
{
SqStack sq(5);
if(sq.IsEmpty())
cout<<"Now the stack is empty,its length is "< cout<<"input the number you want to push into the stack:"< int n,number;
cin>>n;
cout<<"input "< for(int i=0;i {
cin>>number;
sq.Push(number);
}
cout<<"Now the length is "< cout<<"the top elememt is "< sq.Pop();
cout<<"after popping a element,length is "< cout<<"Now the top element is "< sq.Clear();
cout<<"after clearing the stack,length is "< cout<<"Good job!"< system("pause");
return 0;
}