LeetCode707 设计链表

avatar
作者
筋斗云
阅读量:0

前言

题目:707. 设计链表
文档:代码随想录——设计链表
编程语言: C++
解题状态: 代码功底不够,只能写个大概

思路

主要考察对链表结构的熟悉程度,对链表的增删改查,比较考验代码功底以及对链表的掌握。本题中的一些边界条件也要注意。

代码

class MyLinkedList { public:     struct ListNode {         int val;         ListNode* next;         ListNode(int x) : val(x), next(nullptr) {}     };      MyLinkedList() {         _dummyHead = new ListNode(0);         _size = 0;     }          int get(int index) {         if (index > (_size - 1) || index < 0) {             return -1;         }          ListNode* cur = _dummyHead -> next;          while (index--) {             cur = cur -> next;         }          return cur -> val;     }          void addAtHead(int val) {         ListNode* newNode = new ListNode(val);          newNode -> next = _dummyHead -> next;         _dummyHead -> next = newNode;          _size++;     }          void addAtTail(int val) {         ListNode* newNode = new ListNode(val);         ListNode* cur = _dummyHead;          while (cur -> next != nullptr) {             cur = cur -> next;         }         cur -> next = newNode;          _size++;     }          void addAtIndex(int index, int val) {         if (index > _size) {             return;         }          ListNode* newNode = new ListNode(val);         ListNode* cur = _dummyHead;         while (index--) {             cur = cur -> next;         }         newNode -> next = cur -> next;         cur -> next = newNode;          _size++;     }          void deleteAtIndex(int index) {         if (index >= _size || index < 0) {             return;         }          ListNode* cur = _dummyHead;         while (index--) {             cur = cur -> next;         }         ListNode* tmp = cur -> next;         cur -> next = cur -> next -> next;         delete tmp;          _size--;     }      void printLinkedList() {         ListNode* cur = _dummyHead;         while (cur -> next != nullptr) {             cout << cur -> next -> val << " ";             cur = cur -> next;         }         cout << endl;     }  private:     int _size;     ListNode* _dummyHead; }; 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!