这道题主要是效率上的考虑,排序等。
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
typedef struct node{
string id;
string ip;
struct node* ptr;
string mj;
}Node;
int main()
{
int n;
Node* nodeHeader;
string cid,cip;
Node* cur;
Node* temp;
while(cin>>n&&n!=0)
{
nodeHeader=NULL;
for(int i=0;i<n;i++)
{
cin>>cid>>cip;
cur=nodeHeader;
//遍历现有链表,如果有相同ip,即宿主,则是马甲
while(cur!=NULL)
{
if(cur->ip==cip)
{
cur->mj=cid;
break;
}
else
{
cur=cur->ptr;
}
}
//表示没有找到宿主,作为新的节点添加
if(cur==NULL)
{
temp=new Node();
temp->id=cid;
temp->ip=cip;
temp->ptr=NULL;
temp->mj="";
if(nodeHeader==NULL)
{
nodeHeader=temp;
}
else
{
//找位置
Node* pre=nodeHeader;
cur=pre->ptr;
while(cur!=NULL)
{
if(temp->id>cur->id)
{
pre=cur;
cur=cur->ptr;
}
else
{
break;
}
}
if(pre==nodeHeader)
{
if(pre->id>temp->id)
{
nodeHeader=temp;
temp->ptr=pre;
}
else
{
temp->ptr=pre->ptr;
pre->ptr=temp;
}
}
else
{
temp->ptr=pre->ptr;
pre->ptr=temp;
}
}
}
}
cur=nodeHeader;
while(cur!=NULL)
{
cout<<cur->mj<<" is the MaJia of "<<cur->id<<endl;
cur=cur->ptr;
}
//销毁链表
cur= nodeHeader;
while(cur!=NULL)
{
Node* curTemp=cur;
cur=cur->ptr;
delete curTemp;
}
cout<<endl;
}
system("pause");
return 0;
}