序言
小伙伴们都知道栈是一种先进后出的结构,队列是一种后进先出的结构,虽然感觉有点吃饱了撑着(手动狗头),但是我就是想试试看行不行(没错,我就是吃饱了撑的)。
美名曰:加深对这两种结构的理解。
题目描述
1.用队列先进先出的操作来实现栈
实现四种操作:
push(x):压栈
pop():出栈
top() : 获取栈顶元素
empty() : 返回栈是否为空
2.用栈先进后出的操作来实现队列
实现四种操作:
使用栈实现队列的下列操作:
push(x) :将一个元素放入队列的尾部。
pop() :从队列首部移除元素。
peek() : 返回队列首部的元素。
empty() :返回队列是否为空。
题目分析
一.用队列实现栈:
push操作:
因为队列是从front开始输出,也就是说,我们新的元素在插入到tail后,要移动到front的位置。所以原来的队列全体往后移动一位,将新的元素(即队尾元素)插入到front的位置。时间复杂度为O(n)
pup:
因为队列已经调整完位置,所以直接从头开始出队。
top:
不晓得怎么说,和pup同理,返回front就行了
empty:
当front==tail时,队列为空。
附加:
也可以用两个队列实现栈,在两个队列之间相互转换也可以实现栈的操作,但是因为空间复杂度是O(n),所以我没有写这个代码,下面的用栈实现对列就是用的双栈,可以参考一下。
二.用栈实现队列
push操作:
先将stack的所有数出栈并入到stackTemp中,此时stackTemp中的数据是逆序排列,接下来将x入到stack中,在将stackTemp中的数据全部返还stack,实现stack正序的一个过程。时间复杂度为O(n),空间复杂度是O(n)。
pup:
因为栈已经是正序排列,所以直接从top开始出队。
peek:
不晓得怎么说,和pup同理,返回stack[top]就行了
empty:
当top==-1时,队列为空。
代码
一.用队列实现栈:
typedef struct {
int *line;
int front,tail;
} MyStack;
/** Initialize your data structure here. */
MyStack* myStackCreate() {
MyStack *p;
p=(MyStack*)malloc(sizeof(MyStack));
p->line=(int *)malloc(sizeof(int)*100);
p->front=p->tail=0;
return p;
}
/** Push element x onto stack. */
void myStackPush(MyStack* obj, int x) {//突然想到的一个好方法
int temp;
obj->line[(obj->tail)++]=x;
for(int i=0;i<obj->tail-1;i++){
temp=obj->line[i];
obj->line[i]=obj->line[obj->tail-1];
obj->line[obj->tail-1]=temp;
}
}
/** Removes the element on top of the stack and returns that element. */
int myStackPop(MyStack* obj) {
int data=obj->line[0];
for(int i=0;i<obj->tail-1;i++){
obj->line[i]=obj->line[i+1];
}
obj->tail--;
return data;
}
/** Get the top element. */
int myStackTop(MyStack* obj) {
return obj->line[0];
}
/** Returns whether the stack is empty. */
bool myStackEmpty(MyStack* obj) {
if(obj->tail==obj->front)
return true;
else
return false;
}
void myStackFree(MyStack* obj) {
free(obj);
}
一.用栈实现队列:
typedef struct {
int *stack;
int *stackTemp;
int top;
int toptemp;
} MyQueue;
/** Initialize your data structure here. */
MyQueue* myQueueCreate() {
MyQueue *quene;
quene=(MyQueue*)malloc(sizeof(MyQueue));
quene->stack=(int *)malloc(sizeof(int)*100);
quene->stackTemp=(int *)malloc(sizeof(int)*100);
quene->top=-1;
quene->toptemp=-1;
return quene;
}
/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {
int *p,k;
while(obj->top!=-1){
obj->stackTemp[++obj->toptemp]=obj->stack[obj->top--];
}
obj->stackTemp[++obj->toptemp]=x;
while(obj->toptemp!=-1){
obj->stack[++obj->top]=obj->stackTemp[obj->toptemp--];
}
}
/** Removes the element from in front of queue and returns that element. */
int myQueuePop(MyQueue* obj) {
return obj->stack[obj->top--];
}
/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
return obj->stack[obj->top];
}
/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
if(obj->top==-1)
return true;
else
return false;
}
void myQueueFree(MyQueue* obj) {
free(obj);
}