我目前正在搞清楚雙鏈表的實現。聽起來很奇怪,我想重複項目添加到我的鏈接列表。 我按照排序順序將newNode添加到列表中。在雙向鏈表中添加重複項(字符串)
下面的函數不會添加重複節點。
struct Node
{
char name[42];
struct Node *next;
struct Node *prev;
};
void addSorted(struct Node **head, struct Node *newNode)
{
struct Node* current;
// Special case for the head end
if ((*head == NULL) || strcmp((*head)->name, newNode->name) >= 0)
{
newNode->next = *head;
*head = newNode;
}
else
{
// Locate the Node before the point of insertion
current = *head;
while (current->next != NULL &&
strcmp(current->next->name, newNode->name) <= 0)
{
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
struct Node* GetNewNode(char *name)
{
struct Node* newNode = malloc(sizeof (struct Node));
strcpy(newNode->name, name);
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
int main(void)
{
// Some Irrelevant Code
if (strncmp(operator, "a", 1) == 0)
{
temp = GetNewNode(name);
addSorted(&head, temp);
}
}
「以下功能不會添加重複功能」。請澄清。你的意思是你沒有試圖實現,或者你有,但它不工作?如果後者請描述它在做什麼。 – kaylum
我曾嘗試更改比較開關,但我無法實施所需的解決方案。 – user3337714
再次請告訴我們您的程序的當前行爲。它崩潰?它根本不會添加重複節點?它增加了,但有時在錯誤的地方?總是在錯誤的地方? etc ... – kaylum