思路:
1,先初始化两个具有一定存储空间的空栈
2,把元素压入栈1,完成入队操作。由于栈是后进先出的,要实现队列的功能(即先进先出)必须借助另一个栈来实现
3,完成出队的操作,先把栈1的栈顶元素依次弹出并压入栈2,直到栈1的栈低元素。这样栈2中从栈顶到栈底的元素依次是压入栈1的顺序了。这样可以把栈2的元素依次弹出,实现了队列的出队操作。
4,如果,元素没有完全出队,而又有新元素要入队时。此时,栈2中是还有元素没有完全弹出的。同样先把,元素压入栈1,。
5,此时要完成出队列操作,由于栈2中还有元素,意味着栈2中这些元素比新压入栈1的元素先到队列,应该先出队。那么只要栈2中还有元素,就从栈2中弹出元素完成出队操作;否则把栈1中的元素依次弹出并压入栈2。探后从栈2中,弹出元素完成出队操作。
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include <iostream>
#define STACK_INIT_SIZE sizeof(struct stack)*10
#define STACKINCREASWMENT sizeof(struct stack)
struct stack{
int *base;
int *top;
int stacksize;
};
int initStack(stack *s)//构造一个空栈
{
s->base = (int *)malloc(sizeof(struct stack)*STACK_INIT_SIZE);
if(s->base == NULL)
exit(-1);
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
return 1;
}
int push(stack *s,int num)//压栈
{
//先判断栈的内存是否够用,不够用需要从新分配内存
if(s->top - s->base >= s->stacksize - sizeof(struct stack))
s->base = (int *)realloc(s->base,s->stacksize + sizeof(struct stack));
if(s->base == NULL) //内存分配失败
exit(-1);
*s->top++ = num;//注意 优先级
return 1;
}
int pop(stack *s)//弹栈
{
if(s->base == s->top)//空栈,无栈可弹
return -1;
return *(--s->top);
}
/*
stack addElementToQueen(int nums[],int length)
{
if(sizeof(nums)/sizeof(int) != length)
exit(-1);
stack s;
initStack(&s);
for(int i=0;i<length;i++)
{
push(&s,*(nums + i));
}
return s;
}
int deleteElementInQueen(struct stack s1)
{
stack s2;
initStack(&s2);
int n;
if(s2->top - s2->base <= 0)
{
while((s1->top - s1->base) >= 0)
{
n = s1->top;
pop(&s1);
push(&s2,n);
}
}
if(s2->top - s2->base == 0)//换栈失败
return NULL;
n = pop(s2);
return n;
}
*/
void main()
{
stack s1,s2;
initStack(&s1);
initStack(&s2);
int nums[] = {1,2,3,4,5,6};
printf("压入栈 1\n");
for(int i=0;i<6;i++)
{
push(&s1,*(nums + i));
}
printf("出队的顺序为:\n");
while(s1.base != s1.top)
{
while(s1.top - s1.base >1)
push(&s2,pop(&s1));
printf("%d \t",pop(&s1));
while(s2.top - s2.base > 0)
push(&s1,pop(&s2));
}
printf("\n");
}