我正在尝试计算链接列表中 IP 的出现次数,并打印出每个单独的 IP 地址的计数。我可以打印计数,但是当我迭代它时,计数会减少并打印重复项。此外,它们应该按最高登录计数排列在顶部。
我尝试使用数组来实现这一点,方法是为每个 IP 创建副本到数组中,但这并不有效,因为无法预先确定每个用户的数组大小。
预期输出:
IP Address Count
--------------------
97.88.145.98 12
141.219.153.201 4
141.219.209.223 3
141.219.210.114 3
141.219.208.123 1
75.129.96.98 1
141.219.210.180 1
当前输出:
IP Address Occurence
---------------------------
141.219.153.201 4
141.219.153.201 3
97.88.145.98 12
97.88.145.98 11
97.88.145.98 10
97.88.145.98 9
97.88.145.98 8
141.219.210.114 3
141.219.210.114 2
141.219.210.114 1
97.88.145.98 7
97.88.145.98 6
141.219.210.180 1
97.88.145.98 5
97.88.145.98 4
97.88.145.98 3
97.88.145.98 2
75.129.96.98 1
141.219.209.223 3
141.219.209.223 2
141.219.209.223 1
97.88.145.98 1
141.219.153.201 2
141.219.208.123 1
141.219.153.201 1
迭代链表的函数。
bstNode* search(char* key, bstNode* root)
{
int res;
bstNode *leaf = root;
if( leaf != NULL ) {
res = strcmp(key, leaf->data);
if( res < 0)
search( key, leaf->left);
else if( res > 0)
search( key, leaf->right);
else
{
printf("\n'%s' found!\n", key);
printf("---------------------------\n IP Address\tOccurence\n---------------------------\n");
//int count = 0;
IP *temp = leaf->ipHead;
while (temp) {
int tempip = temp->ip;
int ipcount = 0;
uint32_t ip = tempip;
struct in_addr ip_addr;
ip_addr.s_addr = ip;
//bstNode *cpy = leaf;
ipcount = count(temp, tempip);
//temp->count = ipcount;
//temp = leaf;
//printf("The IP address is %s\n C:%d\n", inet_ntoa(ip_addr), ipcount);
printf(" %s\t\t%i\n", inet_ntoa(ip_addr), ipcount);
temp = temp->ipNext;
}
}
}
else printf("\nNot in tree\n");
return leaf;
}
统计出现次数的函数:
int count(IP* start, int item)
{
IP* current = start;
int c = 0;
while (current)
{
if (current->ip == item)
{
c++;
}
current = current->ipNext;
}
//printf("Count is: %d", c);
return c;
}
任何帮助将不胜感激!
最佳答案
函数 search() 中没有任何过滤重复 IP 的条件语句,更准确地说是在“while (temp)”循环附近。
count() 只是在列表中计数。并且有条件仅选择与参数匹配的 ip。
关于c - 如何打印链接列表中的重复项及其出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49461064/