代码随想录算法训练营第三天 | 203.移除链表元素 、 707.设计链表、 206.反转链表

60 阅读1分钟

代码随想录算法训练营第三天 | 203.移除链表元素 、 707.设计链表、 206.反转链表

203.移除链表元素

题目链接:203.移除链表元素

  • 迭代法创建dummyHead.
  • 递归法简单但较难理解

707.设计链表

 class Node {
 ​
 public:
     Node() {
         this->val = 0;
         this->next = nullptr;
     }
     Node(int val){
         this->val = val;
         this->next = nullptr;
     }
     Node* next;
     int val;
 ​
 };
 ​
 ​
 ​
 class MyLinkedList {
 private: 
     Node * dummyHead;
     int size;
 public:
     MyLinkedList() {
         dummyHead = new Node(0);
         size = 0;
     }
     
     int get(int index) {
         cout << "index " << index << endl;
         cout << "size" << size <<endl;
         Node* param_1 = dummyHead->next;
         while(param_1) {
             cout << param_1->val << " ";
             param_1 = param_1->next;
         }
         cout << endl;
         if(index < 0 || index >= size) {
             return -1;
         }
        
         Node* current = dummyHead;
         while(index >= 0) { // index >= 0 false
             current = current->next;
             --index;
         }
         return current->val;
     }
     
     void addAtHead(int val) {
         Node* node = new Node(val);
         node->next = dummyHead->next;
         dummyHead->next = node;
         size++;
     }
     
     void addAtTail(int val) {
         Node* current = dummyHead;
         while(current->next != nullptr) {
             current = current->next;
         }
         current->next = new Node(val);
         size++;
     }
     
     void addAtIndex(int index, int val) {
         if(index > size) {
             return;
         }
         else if(index <= 0) { // index == 0 add before head has the same logic of addAtHead 
             addAtHead(val);
         } else if(index == size) {
             addAtTail(val);
         } else {
             Node* current = dummyHead;
             Node* node = new Node(val);
             while(index--) {
                 current = current->next;
             }
             node->next = current->next;
             current->next = node;
             size++;
         }
     }
     
     void deleteAtIndex(int index) {
         if(index < 0 || index >= size) {
             return;
         }
        
         Node* current = dummyHead;
         while(index--) {
             current = current->next;
         }
         Node* p = current->next;
         current->next = current->next->next;
         delete p;
         size--;
     }
 };
 
 /**
  * Your MyLinkedList object will be instantiated and called as such:
  * MyLinkedList* obj = new MyLinkedList();
  * int param_1 = obj->get(index);
  * obj->addAtHead(val);
  * obj->addAtTail(val);
  * obj->addAtIndex(index,val);
  * obj->deleteAtIndex(index);
  */

206.反转链表

题目链接:206.反转链表

  • 双指针法
  • 递归法