Advertisement
RadioNurshat

Linked List

Feb 15th, 2021
612
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template <typename T>class LinkedList {
  5. private:
  6.     LinkedList(T item) {
  7.         this->Containment = item;
  8.     };
  9.     LinkedList* Next = NULL;
  10.     T Containment;
  11.     LinkedList* getLast() {
  12.         LinkedList* Node = this;
  13.         while (Node->Next != NULL) {
  14.             Node = Node->Next;
  15.         }
  16.         return Node;
  17.     }
  18. public:
  19.     LinkedList() {};
  20.     void push_back(T item) {
  21.         LinkedList* Last = this->getLast();
  22.         Last->Next = new LinkedList(item);
  23.         delete Last;
  24.     }
  25.     T pop_back() {
  26.         return this->getLast()->Containment;
  27.     }
  28.     void push_forward(T item) {
  29.         LinkedList* First = this;
  30.         this->Containment = item;
  31.         this->Next = First;
  32.         delete First;
  33.     }
  34.     T pop_forward() {
  35.         return this->Containment;
  36.     }
  37.     void remove_last() {
  38.         Next = this->Next;
  39.         LinkedList* OneBefore;
  40.         while (Next != NULL) {
  41.             OneBefore = Next;
  42.             Next = Next->Next;
  43.         }
  44.         OneBefore->Next = NULL;
  45.         delete Next;
  46.     }
  47.     void remove_first() {
  48.         LinkedList* Second = this->Next;
  49.         this->Next = Second->Next;
  50.         this->Containment = Second->Containment;
  51.         delete Second;
  52.     }
  53.     int count() {
  54.         LinkedList* Second = this;
  55.         int c = 0;
  56.         while(Second->Next != NULL) {
  57.             Second = Second->Next;
  58.             c++;
  59.         }
  60.         return c + 1;
  61.     }
  62.     T operator[](int number) {
  63.         int i = 0;
  64.         int c = this->count();
  65.         if (i + 1 > c) throw exception("Out of range");
  66.         LinkedList* Second = this;
  67.         while (Second->Next != NULL) {
  68.             if (i == number) {
  69.                 break;
  70.             }
  71.             Second = Second->Next;
  72.             i++;
  73.         }
  74.         return Second->Containment;
  75.     }
  76.  
  77.  
  78.  
  79. };
  80.  
  81.  
  82.  
  83. int main() {
  84.     LinkedList<int> list;
  85.     list.push_back(3);
  86.     list.push_back(4);
  87.     cout << list.count();
  88. }
  89.  
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement