两栈来实现队列功能

用两栈来实现队列功能
首先栈的代码
文件名 stack_list.h
#include<stadio.h>
#include “stack_list.h”

Node* creat_node(TYPE data) //建立一个节点
{
Node* node = malloc(sizoeof(Node));
node->data = data;
node->next =NULL;
return node;
}
// 创建
Stack* creat_stack(void)
{
Stack* stack = malloc(sizeof(Stack));
stack->top = NULL;
stack->len = 0;
return stack;
}

// 销毁
void destory_stack(Stack* stack)
{
while(pop_stack(stack));
free(stack);
}

// 栈空
bool empty_stack(Stack* stack)
{
return NULL == stack->top;
}

// 入栈
void push_stack(Stack* stack,TYPE data)
{
Node* node = creat_node(data);
node->next = stack->top;
stack->top = node;
stack->len++;
}

// 出栈
bool pop_stack(Stack* stack)
{
if(empty_stack(stack)) return false;
Node* node = stack->top;
stack->top = node->next;
free(node);
stack->len–;
return true;
}

// 栈顶
TYPE* top_stack(Stack* stack)
{
if(empty_stack(stack)) return NULL;
return &stack->top->data;
}
然后是栈和队列的
#include <stdio.h>
#include “stack_list.h”

typedef struct Queue
{
Stack* s1;//建立一号栈
Stack* s2;//二号栈
}Queue;

// 创建
Queue* creat_queue(void)
{
Queue* queue = malloc(sizeof(Queue));
queue->s1 = creat_stack();
queue->s2 = creat_stack();
return queue;
}

// 销毁
void destory_queue(Queue* queue)
{
destory_stack(queue->s1);
destory_stack(queue->s2);
free(queue);
}

// 队空
bool empty_queue(Queue* queue)
{
return empty_stack(queue->s1) && empty_stack(queue->s2);
}

// 入队
void push_queue(Queue* queue,TYPE data)
{
push_stack(queue->s1,data);
}

// 出队
bool pop_queue(Queue* queue,TYPE* p)
{
if(empty_queue(queue))
{
*p = -1;
return false;
}
// 如果s2里有元素,直接从s2里面出队
// 如果从s1里提出元素到s2,则必须全部提出
if(empty_stack(queue->s2))
{
while(!empty_stack(queue->s1))
{
TYPE data = *top_stack(queue->s1);
push_stack(queue->s2,data);
pop_stack(queue->s1);
}
}
*p = *top_stack(queue->s2);
return pop_stack(queue->s2);
}

int main()
{
Queue* queue = creat_queue();
for(int i=0; i<10; i++)
{
push_queue(queue,i);
}
for(int i=0; i<5; i++)
{
int top = -1;
pop_queue(queue,&top);
printf(“top:=%d\n”,top);
}
printf("--------------------------\n");
for(int i=10; i<20; i++)
{
push_queue(queue,i);
}
for(int i=0; i<15; i++)
{
int top = -1;
pop_queue(queue,&top);
printf(“top:=%d\n”,top);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值