力扣:用栈实现队列

队列是先进先出,栈是先进后出,本题的关键就在于如何用栈实现先进先出。其中一种方法就是利用双栈。此处使用链栈,应该是因为题目没给出具体的栈的大小。而顺序栈必须提前声明栈的大小。理解双栈的方法不难,于我而言,真正麻烦的是对链栈的操作。代码如下:
typedef struct myStack{
int val;
struct mystack*next;
}MyStack;

typedef struct {
MyStack*s1;
int cnt;
} MyQueue;

/** Initialize your data structure here. */

MyQueue* myQueueCreate() {
MyQueueQ=(MyQueue)malloc(sizeof(MyQueue));
memset(Q,0,sizeof(MyQueue));
return Q;
}

/** Push element x to the back of queue. /
void myQueuePush(MyQueue
obj, int x) {
MyStackn=(MyStack)malloc(sizeof(MyStack));
MyStack*s2=NULL,*t=NULL;
n->val=x;
n->next=NULL;
while(obj->s1)
{
t=obj->s1;
obj->s1=obj->s1->next;
t->next=s2;
s2=t;
}
obj->s1=n;
while(s2)
{
t=s2;
s2=s2->next;
t->next=obj->s1;
obj->s1=t;
}
obj->cnt++;
}

/** Removes the element from in front of queue and returns that element. /
int myQueuePop(MyQueue
obj) {
MyStack*temp=obj->s1;
int num;
obj->s1=obj->s1->next;
obj->cnt–;
num=temp->val;
free(temp);
return num;
}

/** Get the front element. /
int myQueuePeek(MyQueue
obj) {
return obj->s1->val;
}

/** Returns whether the queue is empty. /
bool myQueueEmpty(MyQueue
obj) {
return !obj->cnt;
}

void myQueueFree(MyQueue* obj) {
MyStack*temp=NULL;
while(obj->s1)
{
temp=obj->s1;
obj->s1=temp->next;
free(temp);
}
free(obj);
}

/**

  • Your MyQueue struct will be instantiated and called as such:

  • MyQueue* obj = myQueueCreate();

  • myQueuePush(obj, x);

  • int param_2 = myQueuePop(obj);

  • int param_3 = myQueuePeek(obj);

  • bool param_4 = myQueueEmpty(obj);

  • myQueueFree(obj);
    */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值