SHARE
TWEET

person linked list

sheefoo Jun 4th, 2020 1,125 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #pragma once
  2.  
  3. #include <iostream>
  4.  
  5. struct PersonListNode
  6. {
  7. public:
  8.     Person Value;
  9.     PersonListNode* Next = nullptr;
  10.  
  11.     PersonListNode()
  12.     {
  13.     }
  14. };
  15.  
  16. struct LinkedList
  17. {
  18. public: // private:
  19.     PersonListNode* _head = nullptr;
  20.  
  21.     LinkedList()
  22.     {
  23.     }
  24.  
  25.     void Add(Person* value)
  26.     {
  27.         auto newNode = new PersonListNode();
  28.         newNode->Value = value;
  29.  
  30.         if (_head == nullptr)
  31.         {
  32.             _head = newNode;
  33.             return;
  34.         }
  35.  
  36.         auto last = GetLast();
  37.         last->Next = newNode;
  38.     }
  39.  
  40.     PersonListNode* GetHead()
  41.     {
  42.         return _head;
  43.     }
  44.  
  45.     PersonListNode* GetLast()
  46.     {
  47.         auto h = _head;
  48.  
  49.         while (h->Next != nullptr)
  50.         {
  51.             h = h->Next;
  52.         }
  53.  
  54.         return h;
  55.     }
  56.  
  57.     PersonListNode* ElementAt(int pos)
  58.     {
  59.         auto h = _head;
  60.         if (pos == 0) return h;
  61.  
  62.         int i = 0;
  63.         while (i != pos && h->Next != nullptr)
  64.         {
  65.             h = h->Next;
  66.             i++;
  67.         }
  68.  
  69.         return h;
  70.     }
  71.  
  72.     bool IsEmpty()
  73.     {
  74.         return _head == nullptr;
  75.     }
  76.  
  77.     void RemoveLastNode()
  78.     {
  79.         auto last = GetLast();
  80.  
  81.         if (_head == last)
  82.         {
  83.             _head = nullptr;
  84.             delete last;
  85.             return;
  86.         }
  87.  
  88.         auto preLastNode = _head;
  89.         while (preLastNode->Next != last)
  90.         {
  91.             preLastNode = preLastNode->Next;
  92.         }
  93.  
  94.         delete last;
  95.  
  96.         preLastNode->Next = nullptr;
  97.     }
  98. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top