当前位置: 代码迷 >> 综合 >> 用两个栈实现队列(c语言代码)
  详细解决方案

用两个栈实现队列(c语言代码)

热度:40   发布时间:2024-02-08 14:54:16.0

栈的代码详见:stack的数组实现和测试

队列的数组实现:队列的数组实现(c语言代码)

思想:栈 先进后出,队列先进先出。

/*利用两个栈实现队列*/typedef struct QueueStack
{stack* st1;stack* st2;
}queuestack;

队列尾部添加新元素:st1的栈顶push新元素(因此st1的栈顶是最新写到队列的元素);

队列头部删除元素:

1. 如果栈st2中没元素,则栈st1中栈底是最早写入元素,将栈st1中的元素依次pop出来,写入st2中,则此时,栈st2的栈顶元素是最早写入队列元素,栈st2的栈底是最近写入元素;

2.如果栈st2中有元素,则由1可以知道,st2的栈顶是最早写入队列元素,删除st2的栈顶元素即可。

queue_st.h

#ifndef  __QUEUEST_H_
#define  __QUEUEST_H_/*利用两个栈实现队列*/typedef struct QueueStack
{stack* st1;stack* st2;
}queuestack;queuestack* CreateQueueWithStack();
void DeleteQS(queuestack* qs);
int AppendTail(queuestack* qs);
int DeleteHead(queuestack* qs);
void Qs_showdata_int(queuestack* qs);
#endif

 

queue_st.c

#include "public.h"
#include "stack.h"
#include "queue_st.h"queuestack* CreateQueueWithStack()\
{queuestack* qs = NULL;qs = (queuestack*)malloc(sizeof(queuestack));if(NULL == qs){printf("Malloc erron.\n");return NULL;}qs->st1 = createStack();qs->st2 = createStack();return qs;
}
void DeleteQS(queuestack* qs)
{Destroy(qs->st1);Destroy(qs->st2);
}
void Qs_showdata_int(queuestack* qs)
{int i = 0;if(!StackIsEmpty(qs->st2)){printf("st2 has:\n");for(i = qs->st2->top -1 ; i >= 0; --i){printf("%d	", qs->st2->data[i]);}printf("\n");}if(!StackIsEmpty(qs->st1)){printf("st1 has:\n");for(i = 0 ; i < qs->st1->top; ++i){printf("%d	", qs->st1->data[i]);}printf("\n");}printf("---------------------------\n\n");
}
int AppendTail(queuestack* qs, DataType data)
{if(StackIsFull(qs->st1)){printf("Queue which is completed with two stack is FULLLLL...\n");return -1;}push(qs->st1, data);return 0;
}int DeleteHead(queuestack* qs)
{DataType top_val;if(!StackIsEmpty(qs->st2)){pop(qs->st2);}else{if(!StackIsEmpty(qs->st1)){while(!StackIsEmpty(qs->st1)){top_val = GetTop(qs->st1);push(qs->st2, top_val);pop(qs->st1);}pop(qs->st2);}else{printf("the QueusStack is empty and has no element to delete.\n");return -1;}}return 0;
}

test.c

#include"public.h"
#include"stack.h"
#include"queue.h"
#include "queue_st.h"#if 1
int main()
{queuestack *qs = NULL;int i = 0,size = 0,j = 0;qs = CreateQueueWithStack();size = 101;for(i = 0; i < size; ++i){AppendTail(qs, (i+1));}printf("tail append 100 numbers.\n");Qs_showdata_int(qs);size = 50;for(j = 0; j < size; ++j){DeleteHead(qs);}printf("head delete 50 numbers.\n");Qs_showdata_int(qs);size = 30;for(j = 0; j < size; ++j){AppendTail(qs, (101+j));}printf("tail append 30 numbers\n");Qs_showdata_int(qs);size = 20;for(j = 0; j < size; ++j){DeleteHead(qs);}printf("head delete 20 numbers.\n");Qs_showdata_int(qs);size = 30;for(j = 0; j < size; ++j){AppendTail(qs, (131+j));}printf("tail append 30 numbers\n");Qs_showdata_int(qs);size = 92;for(j = 0; j < size; ++j){DeleteHead(qs);}printf("head delete 90 numbers.\n");Qs_showdata_int(qs);return 0;
}
#endif

 

  相关解决方案