有沒有辦法爲不同的結構編寫單個函數(addnode)?我有這樣的場景:函數addnode爲不同的鏈表結構
typedef struct linkedlist_a *ptr_a;
typedef struct linkedlist_a
{
/* content */
ptr_a next;
} listA;
typedef struct linkedlist_b *ptr_b;
typedef struct linkedlist_b
{
/* content */
ptr_b next;
} listB;
listA *listA_addnode(listA *head, listA *node)
{
listA *temp = head;
if(temp == NULL)
{
temp = node;
}
else if(temp -> next == NULL)
{
temp -> next = node;
}
else
{
while(temp -> next) temp = temp -> next;
temp -> next = node;
}
return head;
}
listB *listB_addnode(listB *head, listB *node)
{
listB *temp = head;
if(temp == NULL)
{
temp = node;
}
else if(temp -> next == NULL)
{
temp -> next = node;
}
else
{
while(temp -> next) temp = temp -> next;
temp -> next = node;
}
return head;
}
如果有兩大系結構是好的,我寫兩個功能,但萬一我有超過2個,我該怎麼辦?
你聲明瞭兩個不同的鏈表來保存不同類型的? – Ifthikhan
如果您在空列表上調用addnode()函數,它將不起作用 - 您需要將頭指向新分配的節點 – Raj