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