Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1. #include <stdexcept>
  2. #include <cassert>
  3. #include "../Headers/LinkedList.h"
  4.  
  5. LinkedList::LinkedList() {
  6.     first = last = nullptr;
  7.     size = 0;
  8. }
  9.  
  10. LinkedList::~LinkedList() {
  11.     while (first) {
  12.         Node* n = first;
  13.         delete first;
  14.         first = n;
  15.     }
  16. }
  17.  
  18. int LinkedList::GetFront() const {
  19.     if (isEmpty()) {
  20.         throw std::runtime_error("List is empty");
  21.     }
  22.     return first->data;
  23. }
  24.  
  25. int LinkedList::GetLast() const {
  26.     if (isEmpty()) {
  27.         throw std::runtime_error("List is empty");
  28.     }
  29.     return last->data;
  30. }
  31.  
  32. void LinkedList::insertFront(int x) {
  33.     Node* node = new Node;
  34.     node->data = x;
  35.     node->next = first;
  36.  
  37.     if (isEmpty()) {
  38.         last = node;
  39.     }
  40.  
  41.     first = node;
  42.     ++size;
  43. }
  44.  
  45. void LinkedList::insertBack(int x) {
  46.     Node* node = new Node;
  47.     node->data = x;
  48.     node->next = nullptr;
  49.  
  50.     if (isEmpty()) {
  51.         first = node;
  52.         last = node;
  53.     } else {
  54.         last->next = node;
  55.         last = node;
  56.     }
  57.     ++size;
  58. }
  59.  
  60. void LinkedList::removeFront() {
  61.     if (isEmpty()) {
  62.         throw std::runtime_error("List is empty");
  63.     }
  64.  
  65.     Node* node = first;
  66.     first = first->next;
  67.     delete node;
  68.  
  69.     if (size == 1) {
  70.         last = first;
  71.     }
  72.     --size;
  73. }
  74.  
  75. bool LinkedList::isEmpty() const {
  76.     return size == 0;
  77. }
  78.  
  79. void LinkedList::insertAfter(Node *it, int x) {
  80.     assert( it != nullptr);
  81.  
  82.     Node* node = new Node;
  83.     node->next = it->next;
  84.     node->data = x;
  85.     it->next = node;
  86.    
  87.     if (it == last) {
  88.         last = node;
  89.     }
  90.  
  91.     ++size;
  92. }
  93.  
  94. void LinkedList::RemoveAfter(Node *it) {
  95.     assert(it != nullptr);
  96.     bool changeLast = (it->next == last);
  97.    
  98.     if (it == last) {
  99.         std::runtime_error("cannot remove");
  100.     }
  101.    
  102.     Node* n = it->next;
  103.     it->next = it->next->next;
  104.     delete n;
  105.    
  106.     --size;
  107. }
  108.  
  109. bool predicate(int val) {
  110.     return val == 5;
  111. }
  112.  
  113. const Node* find(const Node* first) {
  114.     while (first != nullptr && !predicate(first->data)) {
  115.         first = first->next;
  116.     }
  117.     return first;
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement