我正在尝试计算链表中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;
}
任何帮助都会非常感激!
答案 0 :(得分:0)
没有任何条件声明可以在函数search()中过滤重复的IP,更准确地说是在(&temp)&#39; while(temp)&#39;环。
count()只计入列表中。以及只选择与参数匹配的ip的条件。
答案 1 :(得分:0)
您的函数正在计算列表其余部分中ip的出现次数。
所以当你的ip-list await
看起来像
temp
然后循环迭代
( ip1, ip2, ip1, ip2 )
要解决此问题,您必须跟踪每个已经计入的ip: 错了:
count( ip1, ( ip1, ip2, ip1, ip2 )); // => "ip1 2"
count( ip2, ( ip2, ip1, ip2 )); // => "ip2 2"
count( ip1, ( ip1, ip2 )); // => "ip1 1"
count( ip2, ( ip2 )); // => "ip2 1"
右:
ipcount = count(temp, tempip);
printf(...);
当然,必须首先清空簿记数据。