classMyLinkedList { public: /** Initialize your data structure here. */ MyLinkedList() : list_size(0), tail(nullptr) { dummy = new ListNode(NULL); } /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ intget(int index){ if (index < 0 || index >= list_size) return-1; ListNode* cur = dummy->next; //存储当前节点(从0开始) while (index--) { cur = cur->next; } return cur->val; } /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ voidaddAtHead(int val){ ListNode* node = new ListNode(val); node->next = dummy->next; dummy->next = node; list_size++; //节点数自增 if (tail == nullptr) //链表为空时先插入头节点 tail = node; } /** Append a node of value val to the last element of the linked list. */ voidaddAtTail(int val){ ListNode* node = new ListNode(val); if (tail == nullptr) { //tail指针为空,说明当前链表为空(list_size = 0) tail = dummy; } tail->next = node; //添加新节点到链表末尾 tail = node; //tail指向最后一个节点 list_size++; //节点数自增 } /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ voidaddAtIndex(int index, int val){ if (index > list_size || index < 0) return; if (index == 0) //在链表头部插入 addAtHead(val); elseif (index == list_size) //在链表尾部插入 addAtTail(val); else { ListNode* node = new ListNode(val); ListNode* pre = dummy; //存储待插入节点的前一个节点 while (index--) { pre = pre->next; } node->next = pre->next; //待插入节点指向下一个节点 pre->next = node; //待插入节点的前一个节点指向待插入节点 list_size++; //链表长度自增 } } /** Delete the index-th node in the linked list, if the index is valid. */ voiddeleteAtIndex(int index){ if (index >= list_size || index < 0) return; ListNode* pre = dummy; //存储待删除节点的前一个节点 while (index--) { pre = pre->next; } ListNode* cur = pre->next; //暂存待删除的节点 if (cur->next == nullptr) tail = pre; //若待删除的为最后一个节点,尾指针前移 pre->next = cur->next; //待删除节点的前一个节点指向待删除节点的下一个节点,不用区分是否为最后一个节点 list_size--; //链表长度自减 delete cur; //释放已删除的节点空间,注意,其他指向该节点的指针的内容也没了 cur = nullptr; }