gon2

Untitled

Feb 5th, 2018
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdexcept>
  3.  
  4. using namespace std;
  5.  
  6. template <class T>
  7. class SinglyLinkedList {
  8.    private:
  9.     class Node {
  10.        public:
  11.         Node* next;
  12.         T data;
  13.  
  14.         Node(T data, Node* next) {
  15.             this->data = data;
  16.             this->next = next;
  17.         }
  18.  
  19.         ~Node() {
  20.             if (this->next != nullptr) {
  21.                 delete this->next;
  22.             }
  23.         }
  24.     };
  25.  
  26.     Node* head;
  27.     int length;
  28.  
  29.    public:
  30.     SinglyLinkedList() {
  31.         this->head = nullptr;
  32.         this->length = 0;
  33.     }
  34.  
  35.     ~SinglyLinkedList() { delete this->head; }
  36.  
  37.     int size() { return this->length; }
  38.  
  39.     void display() {
  40.         for (Node* node = this->head; node != nullptr; node = node->next) {
  41.             cout << node->data << " -> ";
  42.         }
  43.         cout << "Ø" << endl;
  44.     }
  45.  
  46.     void prepend(T data) {
  47.         this->head = new Node(data, this->head);
  48.         this->length += 1;
  49.     }
  50.  
  51.     void reverse() {
  52.       /* þurfum 3 hnútabreytur, eina fyrir þann sem við ætlum að breyta next á,
  53.          eina fyrir hnútinn á undan og eina fyrir hnútinn á eftir */
  54.       Node* a = this->head->next; //O
  55.       Node* b = this->head->next; //O
  56.       Node* c = this->head; //T
  57.  
  58.       c->next = nullptr; //hausinn verður halinn
  59.  
  60.       for (int i=0; i<this->length-2; i++) { //-2 vegna þess að við stillum hausinn og halann útfyrir
  61.         a = a->next; //L, 2... //geymum hnútinn á eftir til að nota í næstu ítrun
  62.         b->next = c; //T, O... //breytum vísun hnúts í hnútinn á undan
  63.         //stillingar fyrir næstu ítrun:
  64.         c = b; //O, L...
  65.         b = a; //L, 2...
  66.       }
  67.       //stillum hausinn:
  68.       this->head = a;
  69.       this->head->next = c;
  70.     }
  71. };
  72.  
  73. int main() {
  74.     // Skilgreining lista sem inniheldur tákn
  75.     SinglyLinkedList<char> list;
  76.     list.prepend('G');
  77.     list.prepend('3');
  78.     list.prepend('0');
  79.     list.prepend('2');
  80.     list.prepend('L');
  81.     list.prepend('O');
  82.     list.prepend('T');
  83.  
  84.     list.display();
  85.  
  86.     list.reverse();
  87.  
  88.     list.display();
  89.  
  90.     return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment