php app網(wǎng)站建設(shè)武漢seo管理
方法1:原鏈表刪除元素
?偽代碼:
????????首先判斷頭節(jié)點是否是待刪除元素。(頭節(jié)點和其他節(jié)點的刪除方法不一樣)
while(head != null && head->value == target)
//如果鏈表為 1 1 1 1 1,要刪除元素1時用if就會失效
{head = head->next;
}
cur = head;
//為什么不是從head->next開始
//因為不方便刪除鏈表節(jié)點,如果指向head->next的話,head會丟失,不方便刪除鏈表節(jié)點
while(cur != null && cur ->next != null)
{if(cur->next->value == target){cur->next = cur->next->next;}else{cur = cur->next;}
}
return head;
方法2:虛擬頭節(jié)點
? ? ? ? 增加一個虛擬頭節(jié)點,如果刪除的是頭節(jié)點,那么直接刪除就行。
偽代碼:
dumyhead = new();//創(chuàng)建虛擬頭節(jié)點
dumyhead->next = head;
cur = dumy->head;
while(cur->next != null)
{if(cur->next->value = target)cur->next = cur->next->next;elsecur = cur->next;
}
return dumyhead->next;