转载自:http://blog.youkuaiyun.com/tgbus18990140382/article/details/20204999
请设计一个排队系统,能够让每个进入队伍的用户都能看到自己在队中所处的位置和变化。队伍可能随时有人加入和退出,当有人退出影响到用户的位置排名时需要即时反馈到用户。
分析:使用双链表完成该任务比较简单,并且容易扩展实现其他的功能。
1. 当插入时,从队尾插入节点,插入完成以后向每个用户通知即可。
2. 从队列中删除元素时,通过元素的在队列中的位置将其删除,并且将其后的元素的位置依次向前移。
笔者也是尝试解题,如有不正确的地方望大家指出。
#include <stdio.h>
struct NODE
{
int num;
int mark;//the person mark,it is also can be a string.
NODE * pre;
NODE * next;
} * HEAD , * TAIL;
void showQueue();
void join();
void exit( int num );
void main()
{
HEAD = new NODE;
HEAD->num = 0;
HEAD->pre = NULL;
HEAD->next = NULL;
TAIL = HEAD;
// 八个人
join();join();join();join();join();join();join();join();
showQueue();
exit(3);exit(1);exit(6);
showQueue();
}
void showQueue()
{
NODE * pointer = HEAD;
while( pointer!= NULL )
{
printf( "queue number is %d\n" , pointer->num );
pointer = pointer->next;
}
}
void join()
{
NODE * current = new NODE;
current->num = TAIL->num+1;
current->pre = TAIL;
current->next = NULL;
TAIL->next = current;
TAIL = current;
}
void exit( int num )
{
if( num > 0 )
{
NODE * p = HEAD;
NODE * removeNode = NULL;
while( p != NULL )
{
if ( p->num == num )
{
removeNode = p;
break;
}
p = p->next;
}
if ( removeNode != NULL )
{
printf( "%d number exit!\n" , removeNode->num );
//remove node
if ( removeNode->pre != NULL )
{
removeNode->pre->next = removeNode->next;
}
if ( removeNode->next != NULL )
{
removeNode->next->pre = removeNode->pre;
}
//sub queue number
while( removeNode->next != NULL )
{
removeNode->next->num--;
removeNode = removeNode->next;
}
}
else
{
printf( "%d this number is not exist!\n" , num );
}
}
else
{
printf( "please input correct number!\n" );
}
}