Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- template <typename T>//шаблонный класс параметризуемый типом Т
- class List // явл-ся шаблонным и парамитризуется типом Т
- {
- struct Element
- {
- T data;
- Element* next;
- };
- Element *head;
- // Копирующий конструктор
- List(const List& other)
- {
- }
- // Оператор копирующего присваивания
- List& operator=(const List& other)
- {
- }
- public:
- List () // конструктор (по умолчанию списоок пустой)
- {
- head=NULL;
- }
- ~List () // Деструктор
- {
- while (head!=NULL)
- {
- delHead();
- }
- }
- void add (T newel) // добавить в начало элемент
- {
- Element *e;
- e=new Element();//создали новый !пустой! элемент
- e->data=newel;
- e->next=head;
- head=e;
- }
- void delHead()//удаление первого
- {
- if (head!=NULL)
- {
- Element* e=head;
- head=head->next;
- delete e;
- }
- }
- void addTail (T newel)
- {
- if(head==NULL)
- {
- add(newel);
- }
- else
- {
- Element *e;
- e=new Element();
- e->data=newel;
- e->next=NULL;
- Element *k=head;
- while (k->next!=NULL)
- {
- k=k->next;
- }
- k->next=e;
- }
- }
- void delTail()
- {
- if (head!=NULL)
- {
- if (head->next==NULL)
- {
- delHead();
- }
- else
- {
- Element *pred=head;
- Element *k=head->next;
- while (k->next!=NULL)
- {
- pred=k;
- k=k->next;
- }
- pred->next=NULL;
- delete k;
- }
- }
- }
- void print ()//для печати
- {
- Element* k=head;
- cout << '[';
- while (k!=NULL)
- {
- cout << k->data <<' ';
- k=k->next;
- }
- cout << ']' << endl;
- }
- // осталось добавить итератор и проверить его работу
- class Iterator
- {
- friend List<T>; // даем классу списка использовать приватный конструктор
- Element *cur;
- Iterator(Element *start)
- {
- cur = start;
- }
- public:
- T operator*() { return cur -> data; }
- T* operator->() { return &(cur -> data); }
- Iterator& operator++() {
- cur = cur -> next;
- return *this;
- }
- bool operator!=(const Iterator& other) {
- return cur != other.cur;
- }
- bool hasNext() { return cur != NULL ? (cur -> next != NULL) : NULL; }
- };
- Iterator start() const
- {
- return Iterator(head);
- }
- Iterator end() const
- {
- return Iterator(NULL);
- }
- };
- int main()
- {
- List<int> listik;
- listik.print();
- listik.add(123);
- listik.add(101);
- listik.print();
- listik.delHead();
- listik.print();
- listik.addTail(432);
- listik.addTail(10);
- listik.print();
- listik.delTail();
- listik.print();
- //List<int> a;
- //List<int> b(a); //копирующий-конструктор
- //a = b; // копирующее присваивание
- cout << "[";
- for(List<int>::Iterator it = listik.start(); it != listik.end(); ++it) // использование итератора
- {
- cout << *it;
- if (it.hasNext()) cout << ", ";
- }
- cout << "]" << endl;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement