誰能告訴我爲什麼替換功能不起作用?說主叫replace(1,2,列表)。它應搜索節點,如果節點的值爲1,則應創建一個值爲2的新節點來替換它,然後釋放分配給第一個節點的內存。我無法弄清楚=(c - 替換鏈表功能
typedef struct iNode
{
int myInt;
struct iNode* next;
} IntNode, *IntNodePtr;
IntNodePtr insert(int i, IntNodePtr p)
{
IntNodePtr newp = malloc(sizeof(struct iNode));
newp->myInt = i;
newp->next = p;
return newp;
}
IntNodePtr delete(int i, IntNodePtr p)
{
/* End of list check */
if(p == NULL)
return NULL;
/* Check if current node is the one to delete */
if(p->myInt == i)
{
IntNodePtr temp;
temp = p->next;
free(p);
return temp;
}
p->next = delete(i, p->next);
return p;
}
IntNodePtr replace(int i, int j, IntNodePtr p)
{
if(p == NULL)
return NULL;
if(p->myInt == i)
insert(j, p->next);
free(p);
p->next = replace(i, j, p->next);
return p;
}
請注意,您將始終需要將列表中的第一個鏈接傳遞給您的`replace`函數。否則,你會最終打破名單。這也適用於2到3個答案。我知道這可能是假設的,但... – JimR 2011-02-07 03:26:18