【发布时间】:2021-03-14 11:08:03
【问题描述】:
如何只找到列表中出现一次的元素并返回基数?例如,如果我的列表包含 {3,2,1,1,2,4},我希望返回的计数器为4 而不是 6,因为我们不计算重复的数字。 这是我目前写的代码。
struct Node
{
int data;
struct Node *next;
};
int Find_cardinal(struct Node *start)
{
struct Node *ptr1, *ptr2
ptr1 = start;
int counter=0;
/* Pick elements one by one */
while (ptr1 != NULL && ptr1->next != NULL)
{
ptr2 = ptr1;
/* Compare the picked element with rest
of the elements */
while (ptr2->next != NULL)
{
/* If duplicate */
if (ptr1->data == ptr2->next->data)
{
break;
}
else
//do what?
ptr2 = ptr2->next;
}
ptr1 = ptr1->next;
}
return counter;
}
【问题讨论】:
-
标有“//do what?”的地方没有什么可以填写的这将使该功能无需更改其他代码即可工作。这是因为那些地方的代码属于“如果
ptr1->data被重复,那么……”,但是你需要计算那些不重复的东西,所以你需要在上面写着“如果ptr1->data不重复,则计算它”的代码。想一想如何做到这一点。 -
另外,避免编写像
int counter;这样不会初始化它定义的对象的代码。初始化对象,除非有充分的理由不这样做。使用int counter = 0;。如果你不从零开始(或其他已知的起点),你就不能计算任何东西。
标签: c linked-list unique singly-linked-list function-definition