Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
ПРАКТИКУМ_3.doc
Скачиваний:
1
Добавлен:
01.05.2025
Размер:
266 Кб
Скачать
☆

36. Построение циклической очереди статическое распределение памяти

#include "stdafx.h"

#include <ctype.h>

#include <iostream>

using namespace std;

#include <conio.h>

#define SIZE 5 // всего 5 ячеек, начиная с 0

class q_type

{

int queue[SIZE];

int head,tail;

public:

void init();

void put(int num); // вставка элемента

int push(); // выталкивание элемента

};

void q_type::init()

{

head=tail=-1;

}

void q_type::put(int num) // блок вставки в очередь

{

if(tail==-1) head=-1; // для работы по кругу замкнутой очереди

tail++; // хвост

if(tail>(SIZE-1))

{

cout<<"\n Queue is overflow\n";

tail--;

return;

}

queue[tail]=num;

}

int q_type::push() // блок выталкивания из очереди

{

head++; // голова

if(head>tail)

{

cout<<"\n Queue is underflow\n";

return 0;

}

if(tail==head) {tail=-1;} // замыкание очереди на начало

return queue[head]; // извлечение элемента

}

void main()

{

q_type qw;

int i;

qw.init();

for(i=0;i<SIZE;i++) qw.put(i);

for(i=0;i<SIZE;i++) cout <<"\n Item from queue is "<<qw.push()<<"\n";

for(i=0;i<SIZE;i++) qw.put(i);

for(i=0;i<SIZE;i++) cout <<"\n Item from queue is "<<qw.push()<<"\n";

_getch();

}

37. Построение стека символов статическое распределение памяти

#include "stdafx.h"

#include <ctype.h>

#include <iostream>

using namespace std;

#include <conio.h>

#define SIZE 10

class stack

{

char stck[SIZE]; // стек в виде массива

int tos; // вершина стека - индекс массива

public:

stack(); // конструктор

~stack(); // диструктор

void push(char ch); // втолкнуть в стек

char pop(); // вытолкнуть из стека

};

stack::stack()

{

tos=0;

}

stack::~stack()

{

}

void stack::push(char ch)

{

if(tos==SIZE)

{

cout<<"Stack is overflow\n";

return;

}

stck[tos]=ch;

tos++;

}

char stack::pop()

{

if(tos==0)

{

cout<<"Stack is underflow\n";

return 0;

}

tos--;

return stck[tos];

}

int main()

{

stack s1,s2;

int i;

s1.push('a');

s2.push('x');

s1.push('b');

s2.push('y');

for(i=0;i<2;i++) cout <<"Item from stack_1 is "<<s1.pop()<<"\n";

for(i=0;i<2;i++) cout <<"Item from stack_2 is "<<s2.pop()<<"\n";

_getch();

return 0;

}

47