Problem Description
想想双向链表……双向队列的定义差不多,也就是说一个队列的队尾同时也是队首;两头都可以做出队,入队的操作。
现在给你一系列的操作,请输出最后队列的状态;
命令格式:
LIN X X表示一个整数,命令代表左边进队操作;
RIN X 表示右边进队操作;
ROUT
LOUT 表示出队操作;
Input
第一行包含一个整数M(M<=10000),表示有M个操作;
以下M行每行包含一条命令;
命令可能不合法,对于不合法的命令,请在输出中处理;
Output
输出的第一行包含队列进行了M次操作后的状态,从左往右输出,每两个之间用空格隔开;
以下若干行处理不合法的命令(如果存在);
对于不合法的命令,请输出一行X ERROR
其中X表示是第几条命令;
Sample Input
8 LIN 5 RIN 6 LIN 3 LOUT ROUT ROUT ROUT LIN 3
Sample Output
3 7 ERROR
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int data;
struct node *next;
};
int b[100005];
int main()
{
char s[5];
int i,M,k=1;
struct node *tail,*head,*p,*q;//head和tail相当于队列的头指针和尾指针,p和q是游动指针
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;//初始化队列
scanf("%d",&M);
for(i=1;i<=M;i++)
{
scanf("%s",s);
if(strcmp(s,"LIN")==0)
{
int t;
scanf("%d",&t);
p=(struct node *)malloc(sizeof(struct node));
p->data=t;
p->next=NULL;
if(head->next==NULL)
{
tail->next=NULL;
tail=p;
head->next=tail;
}//如果队列中没有一个元素,那就在头指针之后加结点,并且该结点就是tail
else
{
p->next=head->next;
head->next=p;
}//如果有元素的话,就在队头指针之后加入新的结点,尾指针不变
}
else if(strcmp(s,"RIN")==0)
{
int t;
scanf("%d",&t);
p=(struct node *)malloc(sizeof(struct node));
p->data=t;
p->next=NULL;
tail->next=p;
tail=p;//在右面进的元素,直接建立新的结点,连接到队尾结点之后,队尾结点变成这个新结点
}
else if(strcmp(s,"LOUT")==0)
{
if(head->next!=NULL)
{
p=head->next;
head->next=p->next;
free(p);
if(head->next==NULL) tail=head;
}//如果队内还有元素,那就通过游动指针和队头指针把队头元素删除,释放内存
else b[k++]=i;//如果没有,则该语句错误
}
else if(strcmp(s,"ROUT")==0)
{
if(head->next!=NULL)
{
p=head;
q=head->next;
while(q->next!=NULL)
{
q=q->next;
p=p->next;
}
free(q);
tail=p;
tail->next=NULL;
}//如果队内还有元素,那么就通过两个游动指针,一指针指向队尾指针的前一个结点,一指针指向队尾指针,通过改变指向删除队尾指针
else b[k++]=i;//如果没有,则该语句错误
}
else b[k++]=i;
}
p=head->next;
while(p!=NULL)
{
if(p->next==NULL) printf("%d\n",p->data);
else printf("%d ",p->data);
p=p->next;
}//队列的输出
for(i=1;i<=k-1;i++) printf("%d ERROR\n",b[i]);//输出错误语句
return 0;
}