SIAOD / Стек и очередь / Otchyot_stek_i_ochered
.docЛабораторная работа №3.
Тема: Стек и очередь.
Реализация алгоритма «Стек» в С++.
#include <iostream.h>
#include <conio.h>
class stek{
private:
struct list{
int num;
list *next;
};
list *head;
public:
stek();
void pop();
void push(int num);
int output();
~stek();
};
void main(){
stek *object=new stek();
clrscr();
int chose;
do{
clrscr();
cout<<" 1-pop"<<endl;
cout<<" 2-push"<<endl;
cout<<"<1-Exit"<<endl;
cout<<"chose=";
cin>>chose;
if(chose == 1){
if(object->output() == -1)
cout<<"Your stek is empty."<<endl;
object->pop();
if(object->output() == -1)
cout<<"Your stek is empty."<<endl;
}
else if(chose == 2){
int num;
cout<<"num=";
cin>>num;
if(object->output() == -1)
cout<<"Your stek is empty."<<endl;
object->push(num);
if(object->output() == -1)
cout<<"Your stek is empty."<<endl;
}
getch();
}while(chose>0);
delete object;
}
stek::stek(){
head=NULL;
}
stek::~stek(){
list *p;
while(head!=NULL){
p=head;
head=head->next;
delete p;
}
}
void stek::push(int num){
list *temp=new list;
temp->num=num;
temp->next=head;
head=temp;
}
int stek::output(){
if(head == NULL)
return -1;
list *p=head;
while(p!=NULL){
cout<<p->num<<" ";
p=p->next;
}
cout<<endl;
return 1;
}
void stek::pop(){
if(head==NULL)
return;
list *p;
p=head;
int num;
num=p->num;
head=head->next;
delete p;
}
Скрин.
Реализация алгоритма «Очередь» в С++.
#include <iostream.h>
#include <conio.h>
class cls_list{
private:
struct list{
int num;
list *next;
};
list *head;
public:
cls_list();
void pop();
void push(int num);
int output();
~cls_list();
};
void main(){
cls_list *object=new cls_list();
clrscr();
int chose;
do{
clrscr();
cout<<" 1-vivod"<<endl;
cout<<" 2-vvod"<<endl;
cout<<"<1-Exit"<<endl;
cout<<"chose=";
cin>>chose;
if(chose == 1){
if(object->output() == -1)
cout<<"Your course is empty."<<endl;
object->pop();
if(object->output() == -1)
cout<<"Your course is empty."<<endl;
getch();
}
else if(chose == 2){
int num;
cout<<"num=";
cin>>num;
if(object->output() == -1)
cout<<"Your course is empty."<<endl;
object->push(num);
if(object->output() == -1)
cout<<"Your course is empty."<<endl;
}
getch();
}while(chose>0);
delete object;
}
cls_list::cls_list(){
head=NULL;
}
cls_list::~cls_list(){
list *p;
while(head!=NULL){
p=head;
head=head->next;
delete p;
}
}
int cls_list::output(){
if(head == NULL)
return -1;
list *p=head;
while(p!=NULL){
cout<<p->num<<" ";
p=p->next;
}
cout<<endl;
return 1;
}
void cls_list::push(int num){
if(head == NULL){
head=new list;
head->num=num;
head->next=NULL;
}
else{
list *p=head;
while(p->next!=NULL)
p=p->next;
list *temp=new list;
temp->num=num;
p->next=temp;
temp->next=NULL;
}
}
void cls_list::pop(){
if(head==NULL)
return;
list *p=head;
head=head->next;
delete p;
}
Скрин.