今天歸納鏈表的時(shí)候,寫了一個(gè)刪除double linklist的任意數(shù)據(jù),我覺得自己寫的好臃腫,雖然g++過(guò)了,但是總覺得是不是哪里欠妥當(dāng)。。。。。強(qiáng)迫癥,總是感覺代碼是不是不夠精煉。。。。請(qǐng)大神給我提意見。。。自己有python和linux的一點(diǎn)點(diǎn)基礎(chǔ)。。。C才學(xué)一個(gè)月,輕噴。。。一下是delete部分的代碼!struct?Node?*delete_givendata(int?data)
{
????struct?Node?*current?=?head;
????struct?Node?*temp?=?NULL;
????struct?Node?*temp1?=?NULL;
????if?(head?==?NULL)?return?NULL;//empty!
????while?(current?->?data?!=?data)//find?the?data?we?want?to?delete.
????{
????????current?=?current?->?next;
????}
????if?(current?==?head?&&?current?->?next?!=?NULL)//the?first?data?is?that?data?we?want?to?delete
????{
????????head?=?current?->?next;
????????current?->?next?->?prev?=?NULL;
????????free(current);
????????return?head;
????}
????else?if?(current?->?prev?!=?NULL?&&?current?->?next?==?NULL)//the?last?data?is?that?data?we?want?to?delete
????{
????????current?->?prev?->?next?=?NULL;
????????free(current);
????????return?head;
????}
????else?if?(head?->?next?==?NULL)//just?one?data?in?list
????{
????????head?=?NULL;
????????free(current);
????????return?head;
????}
????//the?data?in?(first+1,last-1)
????temp?=?current?->?prev;
????temp1?=?current?->?next;
????temp?->?next?=?temp1;
????temp1?->?prev?=??temp;
????free(current);
????return?head;
}
2 回答

onemoo
TA貢獻(xiàn)883條經(jīng)驗(yàn) 獲得超454個(gè)贊
你這個(gè)代碼第 7 行 while 語(yǔ)句處好像有邏輯問(wèn)題吧? ?你說(shuō)代碼通過(guò)了,我不知道你有沒有進(jìn)行充分地測(cè)試。
這個(gè) while 是為了找到等于 data 值的 node,可你沒考慮找不到的情形。
假設(shè)這個(gè)鏈表中只有一個(gè)首 node,而且它的值還不是 data。那么 while 第一次循環(huán)后 current 就已經(jīng)是 NULL 了,第二次進(jìn)入 while 循環(huán)時(shí)就會(huì)因?yàn)樵L問(wèn) NULL 指針而出錯(cuò)退出。
添加回答
舉報(bào)
0/150
提交
取消