实验内容
1.自己选择顺序或链式存储结构,定义一个空栈类,并定义入栈、出栈、取栈元素基本操作。然后在主程序中对给定的N个数据进行验证,输出各个操作结果。
2.自己选择顺序或链式存储结构,定义一个空栈队列,并定义入栈、出栈、取栈元素基本操作。然后在主程序中对给定的N个数据进行验证,输出各个操作结果。
1、栈——顺序栈的实现:
#include<iostream>
#include<iomanip>
using namespace std;
const int StackSize = 10;
class SeqStack
{
public:
SeqStack();
~SeqStack(){};
void Push(int x);
int Pop();
int GetTop();
int Empty();
private:
int data[StackSize];
int top;
};
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;
}
void main()
{
SeqStack S;
cout<<"此时栈的状态为(空栈为EMPTY;非空栈为NOT EMPTY):";
if(S.Empty())
cout<<"EMPTY"<<endl;
else
cout<<"NOT EMPTY"<<endl;
cout<<"进行插入数据1和2的操作"<<endl;
S.Push(1);
S.Push(2);
cout<<"此时栈顶元素为:"<<endl;
cout<<S.GetTop()<<endl;
cout<<"进行出栈一个数据的操作"<<endl;
S.Pop();
cout<<"此时栈顶元素为:"<<endl;
cout<<S.GetTop()<<endl;
}
执行结果:
2、队列——链队列的实现:
#include<iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
class LinkQueue
{
public:
LinkQueue();
~LinkQueue();
void EnQueue(int x);
int DeQueue();
int GetQueue();
int Empty();
private:
Node *front,*rear;
};
LinkQueue::LinkQueue()
{
Node *s = NULL;
s = new Node;
s -> next = NULL;
front = rear = s;
}
LinkQueue::~LinkQueue()
{
Node *p = NULL;
while(front != NULL)
{
p = front -> next;
delete front;
front = p;
}
}
void LinkQueue::EnQueue(int x)
{
Node *s = NULL;
s = new Node;
s -> data = x;
s -> next = NULL;
rear -> next = s;rear = s;
}
int LinkQueue::DeQueue()
{
Node *p = NULL;
int x;
if(rear == front)
throw"下溢";
p = front -> next;
x = p -> data;
front -> next = p -> next;
if(p -> next == NULL)rear = front;
delete p;
return x;
}
int LinkQueue::GetQueue()
{
if(front != rear)
return front -> next -> data;
}
int LinkQueue::Empty()
{
if(front == rear)
return 1;
else
return 0;
}
void main()
{
LinkQueue Q;
cout<<"此时队列的状态为(空队列为EMPTY,非空队列为NOT EMPTY):";
if(Q.Empty())
cout<<"EMPTY"<<endl;
else
cout<<"NOT EMPTY"<<endl;
cout<<"执行插入数据1和2的操作"<<endl;
try
{
Q.EnQueue(1);
Q.EnQueue(2);
}
catch(char *wrong)
{
cout<<wrong<<endl;
}
cout<<"此时队列的对头元素为:"<<endl;
cout<<Q.GetQueue()<<endl;
cout<<"执行一次出队操作"<<endl;
try
{
Q.DeQueue();
}
catch(char * wrong)
{
cout<<wrong<<endl;
}
cout<<"此时队列的队头元素为:"<<endl;
cout<<Q.GetQueue()<<endl;
}
执行结果为: