力扣 用两个栈实现队列 C

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):

实现 MyQueue 类:

  • void push(int x) 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 false

说明:

  • 你 只能 使用标准的栈操作 —— 也就是只有 push to toppeek/pop from topsize, 和 is empty 操作是合法的。
  • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

示例 1:

输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]

解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

思路:

我们先定义栈,里面有一个数组,一个指针top,和最大承受能力值capacity,我们对栈进行初始化、入栈、出栈、判空、取栈顶、销毁栈操作,销毁栈时我们需要将数组free掉,此外,因为队列是先进先出,而栈是后进先出,要想用栈实现队列,我们需要定义两个栈,s1,s2。s1代表进入的栈,s2代表出来时的栈。我们初始化队列,先为其开辟空间,对队列里的两个栈进行初始化操作。入栈时直接进栈s1,则执行push(obj->s1,x),出栈时我们要考虑出来的栈是否为空,如果为空,我们将栈s1里的栈顶元素压入s2中,最终pop,取最前面的值也就是取栈顶s2,销毁队列时,直接销毁两个栈就可以。

代码:

typedef struct stack{
	int *a;
	int top;
	int capacity;
}stack;
stack * Init(){
	stack *s=malloc(sizeof(stack));
	s->a=(int*)malloc(sizeof(int)*300);
	s->top=0;
	s->capacity=300;
	return s;
}
void Push(stack *s,int x){
	if(s->top==s->capacity){
		return ;
	}
	else{
		s->a[s->top]=x;
		s->top++;
	}
}
void Pop(stack *s){
	if(s->top==0){
		return ;
	}
	else{
		s->top--;
	}
}
int GetTop(stack *s){
	return s->a[s->top-1];
}
bool Empty(stack *s){
	if(s->top==0){
		return true;
	}
	else{
		return false;
	}
}
void Free(stack *s){
	free(s->a);
}
typedef struct {
    stack *s1;
	stack *s2;
} MyQueue;
MyQueue* myQueueCreate() {
    MyQueue* p=malloc(sizeof(MyQueue));
		p->s1=Init();
		p->s2=Init();
		return p;
}
void myQueuePush(MyQueue* obj, int x) {
    Push(obj->s1,x);
}
int myQueuePop(MyQueue* obj) {
    if(Empty(obj->s2)){
			while(!Empty(obj->s1)){
				Push(obj->s2,GetTop(obj->s1));
				Pop(obj->s1);
			}
		}
		int x=GetTop(obj->s2);
		Pop(obj->s2);
		return x;
}

int myQueuePeek(MyQueue* obj) {
    if(Empty(obj->s2)){
			while(!Empty(obj->s1)){
				Push(obj->s2,GetTop(obj->s1));
				Pop(obj->s1);
			}
		}
		return GetTop(obj->s2);
}

bool myQueueEmpty(MyQueue* obj) {
    return Empty(obj->s1)&&Empty(obj->s2);
}

void myQueueFree(MyQueue* obj) {
    Free(obj->s1);
		Free(obj->s2);
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值