classSolution { public: ListNode* removeElements(ListNode* head, int val){ // 删除头节点 while (head != NULL && head -> val == val) { ListNode* tmp = head; head = head -> next; delete tmp; }
// 删除非头节点 ListNode* cur = head; // cur存储要删去的节点的前一个节点 // 要删的节点cur->next不可为空, cur != NULL是考虑空链表的情况 while (cur != NULL && cur -> next != NULL) { if (cur -> next -> val == val) { ListNode* tmp = cur -> next; cur -> next = cur -> next -> next; delete tmp; } else cur = cur -> next; // 后移一位 } return head; } };
classSolution { public: ListNode* removeElements(ListNode* head, int val){ // 创建虚拟头节点 ListNode* dummyHead = newListNode(0); dummyHead -> next = head; // 上面的两行代码:创建虚拟头节点可以简写为: // ListNode* dummyHead = new ListNode(0, head); // 或者ListNode* dummyHead = new ListNode(); // dummyHead -> next = head;
// 统一方法删去值为val的节点 // 从虚拟头节点开始遍历, cur为目标节点的前一个节点 // 此时因为加入了虚拟头节点,因此链表不可能为空,因此不再需要考虑链表为空的判断条件:cur != NULL ListNode* cur = dummyHead; while (cur -> next != NULL) { if (cur -> next -> val == val) { ListNode* tmp = cur -> next; cur -> next = cur -> next -> next; delete tmp; } else cur = cur -> next; }
return cur -> val; } voidaddAtHead(int val){ LinkedList* head = newLinkedList(val); head -> next = _dummyHead -> next; _dummyHead -> next = head; _size ++ ; } voidaddAtTail(int val){ LinkedList* tail = newLinkedList(val);
LinkedList* cur = _dummyHead; // while循环中的条件不能是_size -- ,不然会破坏链表长度的准确性 while(cur -> next != NULL) cur = cur -> next; cur -> next = tail; _size ++ ; } voidaddAtIndex(int index, int val){ if (index > _size || index < 0) return;
LinkedList* cur = _dummyHead; LinkedList* node = newLinkedList(val);
while(index -- ) cur = cur -> next;
node -> next = cur -> next; cur -> next = node; _size ++ ; } voiddeleteAtIndex(int index){ if (index < 0 || index >= _size) return; LinkedList* cur = _dummyHead; while (index -- ) cur = cur -> next; LinkedList* tmp = cur -> next; cur -> next = cur -> next -> next; delete tmp; _size -- ; }