代码应该创建一个双向链表。然后应将 IP 地址列表添加到此列表中,其中包含满足唯一 IP 的次数。然后应该对列表进行排序。对不起,代码在记录时会循环到某个地方。以粗体突出显示该位置(试图这样做:))。PS如果你能帮助我选择排序方法,我会很高兴。我已经做了一个,但是使用快速排序或其他东西会更好吗?
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
using namespace std;
struct IP
{
char b[20];
int count;
};
struct Node
{
IP a;
Node *Next,*Prev;
};
struct List
{
Node *Head,*Tail;
int length;
List():Head(NULL),Tail(NULL){};
};
List* list_new()
{
return (List *)calloc(1, sizeof(List));
}
void list_delete(List* l)
{
while (l->Head)
{
l->Tail=l->Head->Next;
free (l->Head);
l->Head=l->Tail;
}
l->length=0;
}
bool push(List* l, IP a)
{
Node *temp=(Node* ) calloc (1, sizeof(Node));
temp->Next=NULL;
temp->a=a;
if (l->Head!=NULL)
{
temp->Prev=l->Tail;
l->Tail->Next=temp;
l->Tail=temp;
}
else
{
temp->Prev=NULL;
l->Head=l->Tail=temp;
}
return 1;
}
bool pop(List*l, IP* x)
{
(*x)=l->Tail->a;
l->Tail->Prev->Next=NULL;
l->Tail=l->Tail->Prev;
l->length++;
return 1;
}
bool unshift(List*l, IP a)
{
Node *temp=(Node* ) calloc (1, sizeof(Node));
temp->Next=NULL;
temp->a=a;
if (l->Head!=NULL)
{
temp->Next=l->Head;
l->Head->Prev=temp;
l->Head=temp;
}
else
{
temp->Prev=NULL;
l->Head=l->Tail=temp;
}
return 1;
}
bool shift(List* l, IP* x)
{
(*x)=l->Head->a;
l->Head->Next->Prev=NULL;
l->Head=l->Head->Next;
return 1;
}
bool reverse (List* l)
{
Node* temp=l->Head;
Node* swaps=NULL;
l->Tail=l->Head;
while (temp!=NULL)
{
swaps=temp->Prev;
temp->Prev=temp->Next;
temp->Next=swaps;
temp=temp->Prev;
}
if (swaps != NULL) l->Head = swaps->Prev;
return 1;
}
void sort (List* l)
{
int i;
for (i=0; i<l->length; ++i) {
Node* compared = l->Head;
while (compared->Next != NULL) {
if (compared->Next->a.count > compared->a.count) {
IP t = compared->Next->a;
compared->Next->a = compared->a;
compared->a = t;
}
compared = compared->Next;
}
}
}
void Show(List* l)
{
int i;
Node* temp=l->Head;
while (temp!=NULL)
{
cout<<temp->a.b<<" "<<temp->a.count<<"\n";
temp=temp->Next;
}
cout<<"\n";
}
int main ()
{
int i;
char strbuf[1000],chTemp;
IP ipTemp;
bool met;
system("CLS");
List* l = list_new();
FILE* foo;
errno_t err;
err=fopen_s(&foo,"input.txt","r");
if( err == 0 )
{
printf( "The file 'input.txt' was opened\n" );
}
else
{
printf( "The file 'input.txt' was not opened\n" );
}
while (!feof(foo))
{
fgets(strbuf,1000,foo);
fclose(foo);
for (i=0;i++;i<20)
if (strbuf[i]==' ') {strncpy_s( ipTemp.b,strbuf, i);break;}
Node* cur = l->Head;
met=0;
while (cur!=NULL)
{
if (cur->a.b == ipTemp.b)
{
met=1;
cur->a.count++;
break;
}
cur=cur->Next;
}
if (met==0)
{
push(l,ipTemp);
l->Tail->a.count++;
}
}
sort(l);
Show(l);
system("PAUSE");
}