Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Zadachi_OOP_SPIOS_Assembler.doc
Скачиваний:
4
Добавлен:
28.10.2018
Размер:
314.37 Кб
Скачать

24.4 // Сформировать числовой файл и отсортировать его компоненты с помощью двух стеков.

#include <fcntl.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <io.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

// Структура, описывающая элемент стека

struct stack {

int info; stack* prev;

stack() { prev=0; info=0; }

};

// Указатель на вершину стека

stack *stack_top1=0;

stack *stack_top2=0;

// Проверка содержимого вершины стека

int top(stack **stack_top)

{

if((*stack_top)==0)

return(0);

return((*stack_top)->info);

}

// Добавление элемента в стек

void push(stack **stack_top, int value)

{

stack *p = new stack;

p->info = value;

p->prev = *stack_top;

*stack_top = p;

}

// Снятие верхнего элемента стека

char pop(stack **stack_top)

{

char value;

stack *p;

value = (*stack_top)->info;

p = (*stack_top)->prev;

delete *stack_top;

*stack_top = p;

return(value);

}

// Проверка стека на пустоту

int empty(stack **stack_top)

{

if((*stack_top)==0) return(1);

return(0);

}

char buffer[100];

void main()

{

int fh;

unsigned int i, cnt=0, nbytes = 100, bytesread;

/* Open file for input: */

if((fh = _open("file.dat", _O_RDONLY)) == -1)

{

perror("open failed on input file");

exit(1);

}

/* Read in input: */

if((bytesread = _read(fh, buffer, nbytes)) <= 0) {

perror("Problem reading file");

exit(1);

}

char str[100];

memset(str,0,100);

int digit;

for(i=0; i<bytesread; i++) {

if(buffer[i]==0x0a) continue;

else {

sprintf(str, "%c", buffer[i]);

digit = atoi(str);

if(!empty(&stack_top1)) {

if(top(&stack_top1) >= digit)

push(&stack_top1, digit);

else {

while((!empty(&stack_top1))&&(top(&stack_top1) < digit)) {

push(&stack_top2, pop(&stack_top1));

}

push(&stack_top1, digit);

while(!empty(&stack_top2)) {

push(&stack_top1, pop(&stack_top2));

}

}

}

else {

push(&stack_top1, digit);

}

}

}

while(!empty(&stack_top1)) {

printf("%d ", pop(&stack_top1));

}

printf("\n");

_close(fh);

}

25.4 Дан файл символов сформировать дерево поиска описав процедуру удаления элнмента из дерева и функцию подсчета листьев в дереве.

//подключение внешних модулей

#include "stdio.h"

#include "string.h"

#include "iostream.h"

#include "Windows.h"

#include "io.h"

#include "fcntl.h"

#include <sys/stat.h>

struct list{//структура Эл-та дерева

char el;

int count;

list *nextl,*nextr;

};

void del_next(list ** node)

{//удаляет все поддеревья указанного корня

if((*node)->nextl!=NULL)//усли не пусто применяем проц удаления наследников

del_next(&(*node)->nextl);

if((*node)->nextr!=NULL)

del_next(&(*node)->nextr);

delete *node;//удаляем родителя

}

void search_el(char el, list ** node)//ищем элемент для удаления

{

if((*node)->el==el){//если это искомый элемент удаляем

if((*node)->nextl!=NULL)

del_next(&(*node)->nextl);

if((*node)->nextr!=NULL)

del_next(&(*node)->nextr);

delete *node;

}else{

if((*node)->nextl!=NULL)search_el(el,&(*node)->nextl);

if((*node)->nextr!=NULL)search_el(el,&(*node)->nextr);

}

}

int get_list_count(list * node)

//процедура считающая количество листьев в дереве

{

if((node->nextl==NULL)&&(node->nextr==NULL))

return 1;//если нет наследников не то это лист

else

{//иначе считаем листья у наследников

int lc,rc;

lc = rc =0;

if(node->nextl!=NULL) lc = get_list_count(node->nextl);

if(node->nextr!=NULL) rc = get_list_count(node->nextr);

return(lc+rc);//возвращаем общее их количество

}

}

void insert_el(char el, list ** node)//вставка елемента в дерево

{

if(*node == NULL)

{//создаем новый элемент

*node = new list;

(*node)->el = el;

(*node)->nextl = NULL;

(*node)->nextr = NULL;

(*node)->count = 1;

}else

if(el == (*node)->el){

(*node)->count++;

}else

{

if(el>(*node)->el) insert_el(el,&(* node)->nextr); else

insert_el(el,&(* node)->nextl);

}

}

int fh;//переменная заголовка файла

void main()//the main function

{

fh = -1;//file handle

list *fst,*tek;

fst = NULL;//создаем переменную корня дерева

fh = _open( "tmp1.file", _O_WRONLY|_O_CREAT );

//открываем файл для записи

printf("vvedite simvol i = ");

char i;

scanf("%c",&i);

do{

int j = _write(fh,&i,sizeof(char));//заполняем файл

if(j<=0) printf("error write");

printf("Vvedite simvol(konechnii element - !) i = ");

cin>>i;//читаем входной поток

}while(i!='!');

_close(fh);//close file

fh = _open( "tmp1.file",_O_RDONLY );

//открываем файл для чтения

bool is_first = true;//

while(!_eof(fh))

{

_read(fh,&i,sizeof(char));

insert_el(i,&fst);//строим бинарное дерево

}// end of tree construction

insert_el('a',&fst);//вставляем элемент для удаления

printf("list coint - %d",get_list_count(fst));//output string

search_el('a',&fst);//находим и удаляем элемент

}

26.4) // Дан числовой файл. Сформировать массив. Найти в массиве заданный элемент и элемент, равный удвоенному заданному с пом. Алгоритма половинного деления(быстрой сортировки)

#include <io.h>

#include <stdio.h>

#include <stdlib.h>

char buffer[100];

int *a;

void main( void ) {

int fh;

unsigned int i, j, nbytes = 100, bytesread;

char digit[10];

/* Open file for input: */

if((fh = _open("file.dat", _O_RDONLY)) == -1) {

perror("open failed on input file");

exit(1);

}

/* Read in input: */

if((bytesread = _read(fh, buffer, nbytes)) <= 0) {

perror("Problem reading file");

exit(1);

}

a = new int[bytesread];

for(j=0, i=0; i<bytesread; i++) {

if(buffer[i]==0x0a) continue;

sprintf(digit, "%c", buffer[i]);

a[j++] = atoi(digit);

}

fastSort(0,j);

int item, fl=0;

printf("\nInput unknown quantity:\n");

scanf("%d", &item);

for(i=0; i<j; i++) {

if (item==a[i]) { printf("Item = %d was found.\n", item); fl=1; break; }

}

if(!fl) printf("Item = %d was not found.\n", item);

for(fl=0, i=0; i<j; i++) {

if (2*item==a[i]) { printf("Item = %d was found.\n", 2*item); fl=1; break; }

}

if(!fl) printf("Item = %d was not found.\n", 2*item);

delete [ ] a;

}

void fastSort(int l, int r) {

int i = l; int j = r; int x = a[(l+r)/2];

int tmp;

while(i<j) {

while(x>a[i]) { i++; }

while(x<=a[j]) { j--; }

if(i<=j) {

tmp = a[i];

a[i] = a[j];

a[j] = tmp;

i++;

j--;

}

}//while

if(l<j) fastSort(l,j);

if(i<r) fastSort(i,r);

}

// Написать процедура реализации очереди

#include <stdio.h>

// Структура, описывающая элемент очереди

struct turn {

int info;

turn *next;

turn() { next=0; info=0; }

};

// Указатель на голову очереди

turn *head=0;

// Указатель на хвост очереди

turn *tail=0;

// Содержимое головы очереди

int top()

{

if(head==0) return(0);

return(head->info);

}

// Добавление элемента в хвост очереди

void push(int value)

{

turn *p = new turn;

p->info = value;

if(tail!=0) {

tail->next = p;

}

tail = p;

if(head==0)

head = tail;

}

// Удаление элемента с головы очереди

int pop()

{

int value;

turn *p;

value = head->info;

p = head->next;

delete head;

head = p;

return(value);

}

// Проверка очереди на пустоту

int empty()

{

if(head==0) return(1);

return(0);

}

void main()

{

for(int i=0; i<10; i++) {

push(i);

}

while(!empty())

printf("%d ", pop());

printf("\n");

}

27.4) Ф-ции для работы со стеком

#include "iostream.h"

class stack

{

private:

int data;

stack * prev;

public:

static stack * top;

static void push(int a);

static int pop();

static void clear();

};

stack * stack::top=NULL;

void stack::push(int a)

{

stack * newtop;

newtop=new stack;

newtop->data=a;

newtop->prev=top;

top=newtop;

}

int stack::pop()

{

stack * oldtop;

int result;

oldtop=top;

if(oldtop==NULL)return -1;

result=oldtop->data;

top=oldtop->prev;

delete oldtop;

return result;

}

void stack::clear()

{

while(top!=NULL) pop();

}

void main()

{

stack s;

s.push(12);

s.push(21);

cout<<s.pop()<<endl;

s.clear();

cout<<s.pop()<<endl;

}

28.4) Ф-ции для работы с очередью

#include "iostream.h"

class queue

{

private:

int data;

queue * prev;

public:

static queue * first;

static queue * last;

static void Insert(int a);

static int TakeOff();

static void Clear();

};

queue * queue::first=NULL;

queue * queue::last=NULL;

void queue::Insert(int a)

{

queue * newnode;

newnode=new queue;

newnode->data=a;

newnode->prev=NULL;

if(last!=NULL)last->prev=newnode;

last=newnode;

if(first==NULL)first=newnode;

}

int queue::TakeOff()

{

queue * oldfirst;

int result;

oldfirst=first;

if(oldfirst==NULL)return -1;

result=oldfirst->data;

first=oldfirst->prev;

delete oldfirst;

if(first==NULL)last=NULL;

return result;

}

void queue::Clear()

{

while(first!=NULL) TakeOff();

}

void main()

{

queue q;

q.Insert(1);

q.Insert(2);

q.Insert(3);

cout<<q.TakeOff()<<endl;

cout<<q.TakeOff()<<endl;

cout<<q.TakeOff()<<endl;

cout<<q.TakeOff()<<endl;

}

29.4) Ф-ции для работы с бинарным деревом поиска

#include "iostream.h"

class tree

{

private:

int data;

tree * left;

tree * right;

static tree* findleft(tree * subroot,tree * parent,tree ** findparent);

static tree* findright(tree * subroot,tree * parent,tree ** findparent);

public:

static tree * root;

static void insert(int a,tree ** subroot=&tree::root);

static bool search(int a,tree * subroot=tree::root);

static bool del(int a,tree ** subroot=&tree::root);

static void clear();

};

tree * tree::root=NULL;

void tree::insert(int a,tree ** subroot)

{

if(*subroot==NULL)

{

(*subroot)=new tree;

(*subroot)->data=a;

(*subroot)->left=NULL;

(*subroot)->right=NULL;

}

else

{

if(a<(*subroot)->data)

insert(a,&(*subroot)->left);

else

insert(a,&(*subroot)->right);

}

}

bool tree::search(int a,tree * subroot)

{

if(subroot==NULL)return false;

if(subroot->data==a)return true;

if(a<subroot->data)

return search(a,subroot->left);

else

return search(a,subroot->right);

}

bool tree::del(int a,tree ** subroot)

{

if((*subroot)==NULL)return false;

if((*subroot)->data==a)

{

tree *item1,*item2;

if((*subroot)->left!=NULL)

{

item1=findleft((*subroot)->left,*subroot,&item2);

(*subroot)->data=item1->data;

if(item2==(*subroot))

{

item2->left=item1->left;

delete item1;

}

else

{

item2->right=item1->left;

delete item1;

}

return true;

}

if((*subroot)->right!=NULL)

{

item1=findright((*subroot)->right,*subroot,&item2);

(*subroot)->data=item1->data;

if(item2==(*subroot))

{

item2->right=item1->right;

delete item1;

}

else

{

item2->left=item1->right;

delete item1;

}

return true;

}

delete (*subroot);

(*subroot)=NULL;

return true;

}

if(a<(*subroot)->data)

return del(a,&(*subroot)->left);

else

return del(a,&(*subroot)->right);

}

void tree::clear()

{

while(root!=NULL)del(root->data);

}

tree* tree::findleft(tree * subroot,tree * parent,tree ** findparent)

{

if(subroot->right==NULL)

{

(*findparent)=parent;

return subroot;

}

else

return findleft(subroot->right,subroot,findparent);

}

tree* tree::findright(tree * subroot,tree * parent,tree ** findparent)

{

if(subroot->left==NULL)

{

(*findparent)=parent;

return subroot;

}

else

return findright(subroot->left,subroot,findparent);

}

void main()

{

tree t;

t.insert(10);

t.insert(15);

//t.clear();

t.del(8);

t.del(15);

t.del(10);

}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]