gon2

SinglyLinkedList.cpp

Jan 29th, 2018
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdexcept>
  3.  
  4. using namespace std;
  5.  
  6. class SinglyLinkedList {
  7.    private:
  8.     class Node {
  9.        public:
  10.         Node* next;
  11.         char data;
  12.  
  13.         Node(char data, Node* next) {
  14.             this->data = data;
  15.             this->next = next;
  16.         }
  17.     };
  18.  
  19.     Node* head;
  20.     int length;
  21.  
  22.    public:
  23.     SinglyLinkedList() {
  24.         this->head = nullptr;
  25.         this->length = 0;
  26.     }
  27.  
  28.     ~SinglyLinkedList() {
  29.         Node* no = this->head;
  30.         while (no != nullptr) {
  31.           Node* noNext = no->next;
  32.           delete no; //eyðum hnút
  33.           no = noNext; //sækjum næsta
  34.         }
  35.  
  36.         cout << "Kallað hefur verið á eyðinn fyrir listann" << endl;
  37.     }
  38.  
  39.     int size() { return this->length; }
  40.  
  41.     void display() {
  42.         for (Node* node = this->head; node != nullptr; node = node->next) {
  43.             cout << node->data << " -> ";
  44.         }
  45.         cout << "Ø" << endl;
  46.     }
  47.  
  48.     void prepend(char c) {
  49.         Node* pre = new Node(c, this->head); //ný hnútur sem vísar á haus
  50.         this->head = pre; //þessi punktur verður hausinn
  51.         this->length++;
  52.     }
  53.  
  54.     char operator[](int n) {
  55.         if (n < this->length) {
  56.  
  57.           Node* no = this->head;
  58.           for (int i=0; i<n; i++) { //flökkum n sinnum um listann
  59.             no = no->next;
  60.           }
  61.           return no->data; //skilum gögnunum sem n-ti hnúturinn inniheldur
  62.  
  63.         } else {
  64.           //ef n er útfyrir lengd listans (semsagt jafntog eða stærri):
  65.           throw out_of_range("Index out of range");
  66.         }
  67.     }
  68. };
  69.  
  70. int main() {
  71.     // Skilgreining lista sem inniheldur tákn
  72.     SinglyLinkedList list;
  73.     list.prepend('G');
  74.     list.prepend('3');
  75.     list.prepend('0');
  76.     list.prepend('2');
  77.     list.prepend('L');
  78.     list.prepend('O');
  79.     list.prepend('T');
  80.  
  81.     list.display();
  82.  
  83.     cout << "Stak 0 í listanum er " << list[0] << endl;
  84.     cout << "Stak 3 í listanum er " << list[3] << endl;
  85.  
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment