class MyLinkedList { public: //定义链表结构体 struct LinkedNode{ int val; LinkedNode* next; LinkedNode(int val):val(val),next(nullptr){} }; MyLinkedList(){ _head = new LinkedNode(0); len = 0; } int get(int index) { if(index>=len||index<0)return -1; LinkedNode* cnt=_head; while(index--)cnt=cnt->next; return cnt->next->val; } void addAtHead(int val) { LinkedNode* newNode = new LinkedNode(val); newNode->next = _head->next; _head->next = newNode; len++; } void addAtTail(int val) { LinkedNode* newNode=new LinkedNode(val); LinkedNode* cnt=_head; while(cnt->next!=nullptr)cnt=cnt->next; cnt->next=newNode; len++; } void addAtIndex(int index, int val) { if(index>len)return ; if(len==index){ addAtTail(val);return ; } else if(index<0){ addAtHead(val);return ; } LinkedNode* newNode=new LinkedNode(val); LinkedNode* cnt=_head; while(index--)cnt=cnt->next; newNode->next=cnt->next; cnt->next=newNode; len++; } void deleteAtIndex(int index) { if(index>=len||index<0)return ; LinkedNode* cnt=_head; while(index--)cnt=cnt->next; LinkedNode* tp=cnt->next; cnt->next=cnt->next->next; delete tp; len--; } private: int len; LinkedNode* _head; };