Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template<typename T>
- class MyStack2 {
- class Node {
- friend class MyStack2;
- public:
- T data;
- Node* next;
- };
- Node *head;
- size_t topIndex;
- public:
- MyStack2() { head = nullptr; topIndex = 0; };
- void Push2(T d) {
- Node *pv = new Node;
- pv->data = d;
- pv->next = head;
- head = pv;
- topIndex++;
- };
- T Pop2() {
- topIndex--;
- if (topIndex >= 0) {
- T tmp = head->data;
- Node* p_del = head;
- head = head->next;
- delete p_del;
- return tmp;
- }
- else { throw "error"; }
- };
- void MyStack2::Clear_MyStack2()
- {
- if (topIndex < 1) {
- delete head;
- }
- else {
- Node* pt1 = head;
- Node* pt2 = head->next;
- while (pt2 != nullptr) {
- delete pt1;
- pt1 = pt2;
- pt2 = pt2->next;
- }
- topIndex = 0;
- }
- };
- MyStack2& operator=(const MyStack2& ref) {
- if (this != &ref) {
- //оптимизация
- if (topIndex >= ref.topIndex) { //если размер текущего массива >= копируемого,
- Node* pt1 = head;
- Node* pt2 = ref.head;
- for (int i = 0; i < ref.topIndex; ++i) {//то перезаписываем элементы текущего элемента,
- *(pt1 + i) = *(pt2 + i);
- }
- for (int i = ref.topIndex; i < topIndex; ++i) {//остальные удаляем
- delete (pt1 + i);
- }
- }
- else {
- this->Clear_MyStack2();
- this->head = new T[ref.topIndex + 1]; // ??? '=' cannot convert from 'int *' to ...
- topIndex = ref.topIndex;
- Node* pt1 = head;
- Node* pt2 = ref.head;
- for (int i = 0; i < topIndex; ++i) {
- *(pt1 + i) = *(pt2 + i);
- }
- }
- }
- return *this;
- };
- MyStack2& operator=(MyStack2&& ref) {
- this->Clear_MyStack2();
- if (ref.topIndex) {
- head = ref.head;
- }
- return this;
- };
- MyStack2(const MyStack2& ref) {
- *this = ref;
- };
- MyStack2(MyStack2&& ref) {
- this->Clear_MyStack2();
- if (ref.topIndex) {
- head = ref.head;
- }
- };
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement