删除链表指定元素
力扣链接
代码随想录题解
分为两个版本,一个是带有虚拟头节点,一个是不带。
无论是带有还是不带有,我都遇到了这几个问题:
①while循环时的判断,首先要判断当前节点是否为空,接着才能判断当前节点的下一个位置是否为空。
②需要有另一个指针来遍历当前链表。
带有虚拟头节点的代码:
ListNode* removeElements(ListNode* head, int val) {//有虚拟头节点时的处理过程ListNode * vir = new ListNode(0);vir->next = head;//仍然需要另一个指针来遍历ListNode * cur = vir;while(cur!=NULL && cur->next !=NULL){//下一个节点的数据是否是要删除的?if (cur->next->data == val){ListNode* temp = cur->next;cur->next = cur->next->next;delete temp;}else{cur = cur->next;}}head = vir->next;delete vir;return head;
}
不带有虚拟头节点的代码:
ListNode* removeElements(ListNode* head, int val) {//无虚拟头节点时的处理过程//注意这里不是if,如果整条链都要删除,那就不存在if而需要while了while(head->data == val && head != NULL){ListNode * temp = head;head = head->next;delete temp;}//普通的ListNode *cru = head;while(cru->next != NULL && cru!=NULL){//不仅下一个不能为空,本身也不能为空//下一个节点的数据是否是要删除的?if (cru->next->data == val){ListNode* temp = cru->next;cru->next = cru->next->next;delete temp;}else{cru = cru->next;}}return head;
}