Created
December 20, 2016 12:57
-
-
Save attashe/29fdc85fa05fd612876bf39ee864c7fd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdlib.h> | |
#include <time.h> | |
using namespace std; | |
// класс-список, работает с указателями | |
class node | |
{ | |
int info; node* next; | |
public: | |
node(int N, node* tail = NULL) { | |
next = NULL; | |
try { | |
next = N>1 ? new node(N - 1, tail) : tail; | |
info = rand() % 10 + 1; | |
} | |
catch (bad_alloc&) { | |
// если не хватило памяти | |
delete tail; | |
throw; | |
} | |
} | |
~node() { | |
if (next) delete next; | |
} | |
void print() { | |
cout << info << " "; | |
if (next) next->print(); | |
} | |
node* reverse() { | |
return reverse1(NULL); | |
} | |
bool find(int find_info) { | |
for (node* temp = this; temp; temp = temp->next) { | |
if (temp->info == find_info) return true; | |
} | |
return false; | |
} | |
void add(int item) { | |
if (next == NULL) { | |
next = new node(1); | |
next->info = item; | |
} | |
else { | |
this->next->add(item); | |
} | |
} | |
void merge(node* l2) { | |
for (node* cur = l2; cur; cur = cur->next) { | |
if(!this->find(cur->info)) | |
this->add(cur-info); | |
} | |
} | |
private: | |
node* reverse1(node* tail) { | |
node *nx = next; | |
next = tail; | |
return nx ? nx->reverse1(this) : this; | |
} | |
}; | |
// класс-обёртка, об указателях теперь можно не беспокоиться | |
class list { | |
node* l; | |
public: | |
// конструктор | |
list(int N) { | |
l = NULL; | |
if (N>0) | |
l = new node(N); | |
} | |
~list() { if (l) delete l; } | |
void print() { if (l) l->print(); } | |
void reverse() { if (l) l = l->reverse(); } | |
bool find(int info) { if(l) return l->find(info); } | |
void merge(list l2) { if (l) l->merge(l2.l); } | |
}; | |
int main() { | |
try { | |
srand(time(NULL)); | |
list M1(10); | |
M1.print(); | |
cout << M1.find(1) << endl; | |
list M2(10); | |
M2.print(); | |
cout << M2.find(2) << endl; | |
} | |
catch (bad_alloc& ba) { | |
// если не хватило памяти | |
cerr << "Error with dynamic list: " << ba.what() << endl; | |
} | |
cin.get(); | |
// в конце для l удаляется автоматически | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment