classMyLinkedList{public:structListNode{int val;
ListNode* next;ListNode(int val):val(val),next(nullptr){}};MyLinkedList(){
_dummyhead =newListNode(0);
_size =0;}intget(int index){if(index >=0&& index < _size){
ListNode* cur = _dummyhead->next;for(int i =0; i < index; i++){
cur = cur->next;}return cur->val;}elsereturn-1;}voidaddAtHead(int val){addAtIndex(0,val);}voidaddAtTail(int val){addAtIndex(_size,val);}voidaddAtIndex(int index,int val){if(index <0)
index =0;if(index <= _size && index >=0){
ListNode* pre = _dummyhead;
ListNode* cur = _dummyhead->next;for(int i =0;i < index; i++){
pre = cur;
cur = cur->next;}
ListNode* p =newListNode(val);
p->next = cur;
pre->next = p;
_size +=1;}}voiddeleteAtIndex(int index){if(index >=0&& index < _size){
ListNode* cur = _dummyhead;for(int i =0; i < index; i++){
cur = cur->next;}
ListNode* p = cur->next;
cur->next = p->next;delete p;
_size -=1;}}private:
ListNode* _dummyhead;int _size;// 正确声明 _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);
*/