建立一個順序棧,實現棧的壓棧和出棧操作。
阿新 • • 發佈:2019-02-05
標頭檔案:
#ifndef seqstack_H
#define seqstack_H
const int stacksize=10;
class seqstack
{
public:
seqstack();
~seqstack(){}
void push(int x);//將x元素入棧
int pop();//將棧頂元素彈出
int gettop();//取棧頂元素(並不刪除)
int empty();
private:
int data[stacksize];
int top;
};
#endif
子函式:
#include"seqstack.h"//引入類seqstack的宣告
seqstack::seqstack()
{
top=-1;
}
void seqstack::push(int x)
{
if(top==stacksize-1) throw"上溢";
top++;
data[top]=x;
}
int seqstack::pop()
{
int x;
if(top==-1) throw"下溢";
x=data[top--];
return x;
}
int seqstack::gettop()
{
if(top!=-1)
return data[top];
}
int seqstack::empty()
{
if(top==-1) return 1;
else return 0;
}
主函式:
#include<iostream>//引入輸入輸出流
using namespace std;
#include"seqstack.h"
void main()
{
seqstack s;
if(s.empty())
cout<<"棧為空"<<endl;
else
cout<<"棧非空"<<endl;
cout<<"對15和10執行入棧操作"<<endl;
s.push(15);
s.push(10);
cout<<"棧頂元素為:"<<s.gettop()<<endl;
cout<<"執行一次出棧操作"<<s.pop()<<endl;
cout<<"棧頂元素為:"<<s.gettop()<<endl;
}
#ifndef seqstack_H
#define seqstack_H
const int stacksize=10;
class seqstack
{
public:
seqstack();
~seqstack(){}
void push(int x);//將x元素入棧
int pop();//將棧頂元素彈出
int gettop();//取棧頂元素(並不刪除)
int empty();
private:
int data[stacksize];
int top;
};
#endif
子函式:
#include"seqstack.h"//引入類seqstack的宣告
seqstack::seqstack()
{
top=-1;
}
void seqstack::push(int x)
{
if(top==stacksize-1) throw"上溢";
top++;
data[top]=x;
}
int seqstack::pop()
{
int x;
if(top==-1) throw"下溢";
x=data[top--];
return x;
}
int seqstack::gettop()
{
if(top!=-1)
return data[top];
}
int seqstack::empty()
{
if(top==-1) return 1;
else return 0;
}
主函式:
#include<iostream>//引入輸入輸出流
using namespace std;
#include"seqstack.h"
void main()
{
seqstack s;
if(s.empty())
cout<<"棧為空"<<endl;
else
cout<<"棧非空"<<endl;
cout<<"對15和10執行入棧操作"<<endl;
s.push(15);
s.push(10);
cout<<"棧頂元素為:"<<s.gettop()<<endl;
cout<<"執行一次出棧操作"<<s.pop()<<endl;
cout<<"棧頂元素為:"<<s.gettop()<<endl;
}