刪除鏈表指定元素
力扣鏈接
代碼隨想錄題解
分為兩個版本,一個是帶有虛擬頭節點,一個是不帶。
無論是帶有還是不帶有,我都遇到了這幾個問題:
①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;
}