模拟队列问题,我用的是双向循环链表来模拟。
注释@的地方是我出错的地方。
//133 The Dole Queue
#include <iostream>
using namespace std;
struct nobe
{
int value;
nobe * pre, * next;
};
nobe *head, *last;//记录逆时针和顺时针的起点
void creat_list(int);//利用双向循环链表模拟
nobe * couter_clock(int);
nobe * clock(int);
void del(nobe*);//删除节点
int main()
{
//freopen("data.txt", "r", stdin);
int N, k, m;
while (scanf("%d%d%d", &N, &k, &m) && N)
{
creat_list(N);
while (N > 0)//@
{
nobe *x = couter_clock(k);
nobe *y = clock(m);
if(x == y)//点到了同一个节点
{
printf("%3d", x->value);
del(x);
N--;
if(N != 0)//@最后一个不能输出,
printf(",");
}
else
{
printf("%3d%3d", x->value, y->value);
N -= 2;
del(x);
del(y);
if(N != 0)
printf(",");
}
}
printf("\n");
}
return 0;
}
void creat_list(int n)
{
int i = 2;
nobe *s = new nobe, *p = NULL;
s->value = 1;
head = s;//初始化头结点
p = s;
while (i <= n)
{
s = new nobe;
s->value = i++;
s->pre = p;
p->next = s;
p = s;
}
last = p;//得到尾节点
head->pre = last;//连接头尾节点
last->next = head;
}
nobe * couter_clock(int k)
{
nobe *s = head->pre;
while (k--)
s = s->next;
head = s->next;
return s;
}
nobe * clock(int m)
{
nobe *s = last->next;
while(m--)
s = s->pre;
last = s->pre;
return s;
}
void del(nobe *s)
{
if(head == s)//@如果head刚更新的节点正好是要删除的,那么指向下一个
head = head->next;
if(last == s)
last = last->pre;
s->pre->next = s->next;
s->next->pre = s->pre;
delete s;
s = NULL;
}