链接数统计模拟程序
对于单网卡主机,每一组[端口号、IP地址、本地],可以对应一条链接,例如链接到[端口号、IP地址、远程],设计一个程序,统计每个本地端口,各产生了多少链接以供查询。
基本要求:能够实现插入(新建一个链接),删除(中断一个已有链接),查询(查询一个已有链接)功能。
提高要求:程序应保持较小的时间复杂性和空间复杂性。
设计提示:[端口号、IP地址、是否本地?]体现为一个结构体,例如端口号可以定义为int型, IP地址可以定义为String类型,是否本地体现为bull类型,ture表示本地,false表示远程。任意[端口号A、IP地址A、TURE]和[端口号B、IP地址B、FALSE]之间的链接体现为有向图的形式,因此数据结构和算法应体现为对有向图结点的插入、删除和查询。假定网络中已经存在了许多链接,即初始图已经建立。
本地网卡A[100  192.168.0.1  1]---->远程网卡A[101  10.20.0.1    0] 
                                    远程网卡B[102  10,21,1,109  0] 

本地网卡B[200  1.168.0.123  1]---->远程网卡C[10  10.20.0.1    0] 
                                    远程网卡D[12  10,21,1,10  0] 

插入【100,103】------>插入到本地网卡A所组成的有向图中,并位于本地网卡之后。 
插入【300,100】------>新建本地网卡及远程网卡 
删除【100,101】------>删除远程网卡A对应的节点 
查找【100,102】------>返回是否找到 

以下是我写的程序: 
#include <iostream> 
#include <string> 
using namespace std; 

struct Port //网卡节点 

int port; //端口号 
string ip; //IP地址 
bool locial; //是否本地 
Port* next; //下一个端口地址 
}; 

class Link //链接 

protected: 
Port** Start; 
int Num; //预设本地端口的上限 
public: 
Link(int Size); 
~Link(); 
void Insert(int porta,int portb); //插入链接 
void Delete(int porta,int portb); //删除链接 
bool Search(int porta,int portb,int sear,int dele,int ins); //查找链接 
}; 

Link::Link(int Size=10) 

Num=Size; 
Start=new Port* [Num]; 
for (int i=0;i <10;i++) 

Start[i]=NULL; 



Link::~Link() 

Port* p,*q; 
for (int i=0;i <Num;i++) 

p=Start[i]; 
q=p; 
while (p) 

p=p->next; 
delete q; 
q=p; 


delete []Start; 


void Link::Insert(int porta,int portb) 

if (Search(porta,portb,0,0,1)) 
cout < <endl < <"EXISTED!"; 
else 
cout < <endl < <"INSERTED!"; 



void Link::Delete(int porta,int portb) 

if (Search(porta,portb,0,1,0)) 
cout < <endl < <"DELETED!"; 
else 
cout < <endl < <"NOT EXSIT!"; 


bool Link::Search(int porta,int portb,int sear=0,int dele=0,int ins=0) //Sear=1 查找  dele=1 删除 
{ //ins=1  插入 
for (int i=0;(i <Num)&&(Start[i]!=NULL);i++) 

Port* s=Start[i]; 
Port* temp=NULL; 
s=s->next; //s指向本地IP 
if (s->port==porta) //与本地IP一致 

while(s->next!=NULL) //检索远程IP 

temp=s->next; 
if (temp->port==portb) 

if (dele==1) //找到链接删除 

s->next=temp->next; 
delete temp; 
return 1; 

if (sear==1) 

cout < <endl < <"FOUND!"; 
return 1; 



if (ins==1) //存在本地端口的Insert() 

string i; 
s->next=new Port; 
s=s->next; 
s->port=portb; 
cout < <endl < <"PLEASE INPUT IP: "; 
cin>>i; 
s->ip=i; 
s->locial=0; 
s->next=NULL; 
return 0; 




if (ins==1) //不存在本地端口的Insert() 

string s; 
Port* temp=new Port; 
temp->port=porta; 
temp->locial=1; 
cout < <endl < <"PLEASE INPUT IP: "; 
cin>>s; 
temp->ip=s; 
Start[i]=temp; 
Port* n=new Port; 
temp->next=n; 
n->port=portb; 
cout < <endl < <"PLEASE INPUT IP: "; 
cin>>i; 
n->ip=i; 
n->locial=0; 
n->next=NULL; 
return 0; 


if (dele==1) 
return 0; 
cout < <endl < <"NOT EXIST!"; 
return 0;