我正在尝试从链接列表中删除重复项。用户将插入一个值,然后程序将检查用户在链表中的输入和值是否相同。如果它类似,它将删除并在链表中只留下一个。对于例如linkedlist = 10 100. user = 10。结果= 10 100而不是10 10 100。
int insertSorted(LinkedList *ll, int item)
{
ListNode *cur = ll->head;
int size = ll->size;
int i;
for (i = 0; i <= size; i++)
{
if ((size - i) == 0 || item < cur->item)
{
insertNode(ll, i, item); // function to insert the value into Linkedlist
return i;
}
cur = cur->next;
}
ListNode *current = ll->head;
while (current->next != NULL)
{
if (current->item == current->next->item)
{
ListNode *nextNext = current->next->next;
free(current->next);
current->next = nextNext;
}
else
{
current = current->next; // only advance if no deletion
}
}
return -1;
}
答案 0 :(得分:0)
如果您在插入后总是返回,则无法访问删除副本的代码。我认为你需要改为break
。
另外,删除元素时,在哪里修改链表的大小? 如果我理解正确,应该减1。
此外,由于您在每次插入后都要清除重复内容,因此在删除循环中不需要条件推进
答案 1 :(得分:0)
当您插入新节点(示例中的值为10)时,然后return i;
,制作其余代码,我想检查重复项是否不执行。