我一直在做一个队列并试图管理它。我需要一个队列来记录我的udp单服务器/多客户端应用程序中的活动客户端(我不得不使用udp,因此请不要建议转移到tcp)。从队列中删除一个节点
有单个服务器和x个客户端。每当客户端发送其第一条消息时,该客户端的IP号码和端口号就被push()到队列中。
然后,在每隔5秒后,服务器pop()的IP和端口号从队列中发出,并使用此IP和端口号向客户端发送消息。如果客户端在特定的时间内回复,它被认为是“活动的”,但如果在超时时间内没有从客户端接收到repy,则客户端被认为是死的,并且必须从队列中移除。
现在的问题是如何删除这个节点。一种选择是简单地在此节点的位置添加NULL,但我想从队列中彻底删除此节点。
任何建议都比欢迎。
下面是我的代码:
struct node
{
int rollno;
struct node*n;
};
struct node* create()
{
struct node*q;
q=(struct node*)malloc(sizeof(struct node));
return q;
}
void push(struct node*cur)
{
if(head==NULL)
{
head = cur;
tail = cur;
start = cur; //keeps a track of first node
}
else
{
struct node*f;
f=head;
head->n = cur;
head=head->n; //keep updating head
}
}
struct node* pop()
{
struct node*p;
struct node*s = NULL;p = tail;
if (p == head && tail != head) /*if at the end of list, display starting from first element as Queue is FIFO*/
{
p = start;
tail=p->n;
s = p;
display(s);
return s;
}
if(p == NULL)
{
if (start == NULL) //if no emelemt yet in the Queue
return NULL;
else // if at the End of list, go back to start
{
p = start;
tail=p->n;
s = p;
}
}
else
{
tail=p->n; //keep updating tail
s = p;
}
display(s);
return s;
}
void main()
{
while(1)
{
//if new client
struct node*j;
j = create();
// j= ip and port of client.
j->n=NULL;
push(j);
//after every 5 secs
{
pop();
//if client fails to reply
{
delete node.
}
}
}
}
虽然与你的问题没有关系,你是否在函数'push'的'else'部分出现了错误? –
@Ayesha“完全删除”是什么意思?你想知道免费函数 - http://www.cplusplus.com/reference/cstdlib/free/ –
你怎么创建一个新的节点呢?没有看到新对象的内存分配,只要分配NULL即可。 另外,push和pop看起来很像可以用于堆栈实现的东西,而不是队列。 – Nobilis