leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0707.cpp (1556B)


      1 class MyLinkedList {
      2     struct Node {
      3         int val;
      4         Node *next;
      5 
      6         Node(int val, Node *next = nullptr) : val(val), next(next) {}
      7     };
      8 
      9     Node *head = nullptr, *tail = nullptr;
     10     int size = 0;
     11 
     12   public:
     13     MyLinkedList() {}
     14 
     15     int get(int index) {
     16         if (index >= size) return -1;
     17 
     18         Node *p = head;
     19         while (index--)
     20             p = p->next;
     21         return p->val;
     22     }
     23 
     24     void addAtHead(int val) {
     25         if (!head)
     26             head = tail = new Node(val);
     27         else
     28             head = new Node(val, head);
     29         size++;
     30     }
     31 
     32     void addAtTail(int val) {
     33         if (!head)
     34             head = tail = new Node(val);
     35         else
     36             tail = tail->next = new Node(val);
     37         size++;
     38     }
     39 
     40     void addAtIndex(int index, int val) {
     41         if (index > size) return;
     42 
     43         Node *p = head;
     44         size++;
     45 
     46         if (index == 0) {
     47             addAtHead(val);
     48             return;
     49         }
     50 
     51         while (--index)
     52             p = p->next;
     53         p->next = new Node(val, p->next);
     54         if (p == tail) tail = p->next;
     55     }
     56 
     57     void deleteAtIndex(int index) {
     58         if (index >= size) return;
     59 
     60         Node *t, *p;
     61         size--;
     62 
     63         if (index == 0) {
     64             cout << "head" << endl;
     65             t = head;
     66             head = head->next;
     67             delete t;
     68             return;
     69         }
     70 
     71         p = head;
     72         while (--index)
     73             p = p->next;
     74 
     75         t = p->next;
     76         p->next = p->next->next;
     77         if (t == tail) tail = p;
     78         delete t;
     79     }
     80 };