我正在尝试从链表中删除重复项。用户将插入一个值,然后,程序将检查用户的输入和链表中的值是否相同。如果它是相似的,它将删除并只在链表中保留一个。例如linkedlist=10 100。user=10。outcome=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;
}发布于 2017-10-22 01:33:35
如果您总是在插入之后返回,则无法到达删除重复项的代码。我认为你需要用break代替。
另外,当你删除一个元素时,你在哪里修改链表的大小?如果我理解正确的话,应该减1。
此外,由于每次插入后都要清除重复项,因此不需要在deleting循环中进行条件推进
发布于 2017-10-22 01:38:06
当您插入新节点(在您的示例中值为10 )时,然后执行return i;,使其余的代码不被执行,我认为这将检查重复项。
https://stackoverflow.com/questions/46865787
复制相似问题