我的代碼的主要目的是從用戶那裡獲取數據,然後搜索單鍊錶以找到目標,然後刪除所有等於目標的節點。這也是基礎單鍊錶:
typedef struct Node
{
int data;
struct Node *next;
}no;
輸入: 1, 2, 3, 2, 5 --> to delete= 2
所以新的鍊錶是:1, 3, 5
void* toDElduplicatedlinkedlist (no* firstNode, int target)
{
no* current = firstNode;
no* ptemp;
while ( NULL != current->next)
{
if (firstNode->data == target)
{
current = firstNode->next;
free(firstNode);
}
else if (current->next->data == target)
{
ptemp = current->next;
current->next= current->next->next;
free(ptemp);
}
current = current->next;
}
這是我寫的刪除功能。它適用於鏈接列表中間的目標項目,但是當列表的firstNode
頭部是目標時,它要么不刪除它要么丟失頭部地址,我嘗試了很多方法來保存頭部的列表,這樣它就不會丟失它。
它也不適用於最後一個節點是目標的情況。
我一直在努力解決這個問題,但我無法解決它,所以如果有人幫助我解決這個問題,我會很高興和感激。
對於初學者來說,儘管它的返回類型是void *
.
這個while循環
while ( NULL != current->next)
如果為空列表調用函數,則可以調用未定義的行為。
當列表只包含一個節點時,while 循環也會被跳過。
或者例如,如果第一個節點包含一個等於參數目標的值,那麼在循環的第一次迭代中,指向的節點將被釋放。但是在循環的下一次迭代中,您將再次檢查已刪除的節點
if (firstNode->data == target)
{
current = firstNode->next;
free(firstNode);
}
還有一個會調用未定義的行為。
可以通過以下方式聲明和定義該函數
void toDElduplicatedlinkedlist( no **firstNode, int target )
{
while ( *firstNode )
{
if ( ( *firstNode )->data == target )
{
no *tmp = *firstNode;
*firstNode = ( *firstNode )->next;
free( tmp );
}
else
{
firstNode = &( *firstNode )->next;
}
}
}
如果在函數的調用者中你有
no *firstNode;
然後該函數被稱為
toDElduplicatedlinkedlist( &firstNode, target );
即指向列表第一個節點的指針是通過引用傳遞的。
定義函數的另一種方法如下
no * toDElduplicatedlinkedlist( no *firstNode, int target )
{
while ( firstNode && firstNode->data == target )
{
no *tmp = firstNode;
firstNode = firstNode->next;
free( tmp );
}
if ( firstNode != NULL )
{
for ( no *current = firstNode; current->next != NULL; )
{
if ( current->next->data == target )
{
no *tmp = current->next;
current->next = current->next->next;
free( tmp );
}
else
{
current = current->next;
}
}
}
return firstNode;
}
在這種情況下,該函數被稱為
firstNode = toDElduplicatedlinkedlist( firstNode, target );
最後該函數也可以通過以下方式定義
no * toDElduplicatedlinkedlist( no *firstNode, int target )
{
for ( no **current = &firstNode; *current; )
{
if ( ( *current )->data == target )
{
no *tmp = *current;
*current = ( *current )->next;
free( tmp );
}
else
{
current = &( *current )->next;
}
}
return firstNode;
}
並以與上圖相同的方式調用,即
firstNode = toDElduplicatedlinkedlist( firstNode, target );
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句