//nyoj511移动小球
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *pre, *rear;
}Lnode;//结点
Lnode *creat_list(Lnode *head, int num)//创建不带头结点的双循环链表
{
Lnode *current, *phead;
phead = head;
int i;
for(i = 2; i <= num; i++)//从第二个结点创建,可以避免第一个结点单独处理的问题
{
current = (Lnode *)malloc(sizeof(Lnode));
if(current == NULL)
{
printf("no memory available\n");
exit(1);
}
current->data = i;
current->rear = current->pre = NULL;
phead->rear = current;
current->pre = phead;
phead = current;
}
current->rear = head;//创建完成后将链表的首和尾链接起来
head->pre = current;
return head;
}
Lnode *move_a_list(Lnode *head, int x, int y)
{
Lnode *phead_x, *phead_y, *move_node;
phead_x = head;
phead_y = head;
while(phead_x->data != x)
phead_x = phead_x->rear;
move_node = phead_x;
phead_x->pre->rear = phead_x->rear;//不需要free只需要移动位置就行
phead_x->rear->pre = phead_x->pre;
while(phead_y->data != y)
phead_y = phead_y->rear;
phead_y->pre->rear = move_node;
move_node->pre = phead_y->pre;
move_node->rear = phead_y;
phead_y->pre = move_node;
return head;
}
Lnode *move_b_list(Lnode *head, int x, int y)
{
Lnode *phead_x, *phead_y, *move_node;
phead_x = head;
phead_y = head;
while(phead_x->data != x)
phead_x = phead_x->rear;
move_node = phead_x;
phead_x->pre->rear = phead_x->rear;
phead_x->rear->pre = phead_x->pre;
while(phead_y->data != y)
phead_y = phead_y->rear;
phead_y->rear->pre = move_node;
move_node->rear = phead_y->rear;
move_node->pre = phead_y;
phead_y->rear = move_node;
return head;
}
void print_q_list(Lnode *head, int x, int y)
{
Lnode *phead;
phead = head;
while(phead->data != y)
phead = phead->rear;
if(x == 1)
printf("%d\n", phead->rear->data);
else
printf("%d\n", phead->pre->data);
}
/*void print_list(Lnode *head)
{
Lnode *phead;
phead = head;
printf("%d\t", phead->data);
phead = phead->rear;
while(phead != head)
{
printf("%d\t", phead->data);
phead = phead->rear;
}
}*/
int main()
{
int n, num, m, x, y;
scanf("%d", &n);
Lnode *head = NULL;
char ch;
head = (Lnode *)malloc(sizeof(Lnode));
if(head == NULL)
{
printf("no memory available\n");
exit(1);
}
head->data = 1;
head->rear = head->pre = NULL;//在主函数里创建第一个结点,注意这里是赋为NULL
while(n--)
{
scanf("%d%d", &num, &m);
head = creat_list(head, num);
while(m--)
{
getchar();
scanf("%c%d%d", &ch, &x, &y);
if(ch == 'A')
head = move_a_list(head, x, y);
else if(ch == 'B')
head = move_b_list(head, x, y);
else
print_q_list(head, x, y);
}
}
// print_list(head);
return 0;
}