双端队列
Push(X,D):将元素X插入到双端队列D的头
bool Push( ElementType X, Deque D )
{
if((D->Rear - D->Front + D->MaxSize)%D->MaxSize != D->MaxSize - 1)
{
D->Front = (D->Front - 1 + D->MaxSize)%D->MaxSize;
D->Data[D->Front] = X;
}
else return false;
return true;
}
Pop(D):删除双端队列D的头元素,并返回
ElementType Pop( Deque D )
{
if(D->Rear != D->Front)
{
ElementType a = D->Data[D->Front];
D->Front = (D->Front + 1)%D->MaxSize;
return a;
}
else return ERROR;
}
Inject(X,D):将元素X插入到双端队列D的尾部
bool Inject( ElementType X, Deque D )
{
if((D->Rear - D->Front + D->MaxSize)%D->MaxSize != D->MaxSize - 1)
{
D->Data[D->Rear] = X;
D->Rear = (D->Rear + 1)%D->MaxSize;
}
else return false;
return true;
}
Eject(D):删除双端队列D的尾部元素,并返回
ElementType Eject( Deque D )
{
if(D->Rear != D->Front)
{
D->Rear = (D->Rear - 1 + D->MaxSize)%D->MaxSize;
ElementType a = D->Data[D->Rear];
return a;
}
else return ERROR;
}
堆栈模拟队列
设已知有两个堆栈S1和S2,请用这两个堆栈模拟出一个队列Q。
所谓用堆栈模拟队列,实际上就是通过调用堆栈的下列操作函数:
•int IsFull(Stack S):判断堆栈S是否已满,返回1或0;
•int IsEmpty (Stack S ):判断堆栈S是否为空,返回1或0;
•void Push(Stack S, ElementType item ):将元素item压入堆栈S;
•ElementType Pop(Stack S ):删除并返回S的栈顶元素。
实现队列的操作,即入队void AddQ(ElementType item)和出队ElementType DeleteQ()。
源代码:
#include<stdio.h>
//#include<algorithm>
#include<stdlib.h>
#include<string.h>
//using namespace std;
struct SNode{
int num;
struct SNode * next;
};
typedef struct SNode * STACK;
STACK create()
{
STACK shead = (STACK)malloc(sizeof(struct SNode));
shead->next = NULL;
return shead;
}
void push(STACK S,int number)
{
STACK snew = (STACK)malloc(sizeof(struct SNode));
snew->num = number;
snew->next = S->next;
S->next = snew;
}
int pop(STACK S)
{
STACK p;
int number;
p = S->next;
number = p->num;
S->next = p->next;
free(p);
return number;
}
int main(void)
{
STACK s1 = create();
STACK s2 = create();
int n1,n2;
scanf("%d%d",&n2,&n1);
int count1 = 0,count2 = 0;
while(1)
{
char ch;
int num;
scanf("%c",&ch);
if(ch == 'A')
{
scanf("%d",&num);
getchar();
if(count1 < n1)
{
push(s1,num);
count1++;
}
else
{
printf("ERROR:Full\n");
}
}
else if(ch == 'D')
{
if(count2 > 0)
{
printf("%d\n",pop(s2));
count2--;
}
else
{
printf("ERROR:Empty\n");
}
}
else if(ch =='T')
{
break;
}
if(count1 == n1 && count2 == 0)
{
while(count1 != 0)
{
push(s2,pop(s1));
count1--;
count2++;
}
}
}
return 0;
}