栈和队列的相关经典题目
1.怎么用两个栈来模拟实现一个队列
代码实现:
typedef char ELEMTYPE;
typedef struct TwoStack_toQueue//
{stack<ELEMTYPE> S1;//栈1stack<ELEMTYPE> S2;//栈2
}TwoStack_toQueue;typedef struct TwoQueue_toStack
{queue<ELEMTYPE> Q1;queue<ELEMTYPE> Q2;
}TwoQueue_toStack;//1.用两个栈来模拟实现一个队列
//入队
bool Push_TSTQ(TwoStack_toQueue* tstq, ELEMTYPE ch)
{tstq->S1.push(ch);return true;
}//出队
bool Pop_TSTQ(TwoStack_toQueue* tstq)
{if (tstq->S1.empty() && tstq->S2.empty())//先保证有元素return false;if (tstq->S2.empty())//看看栈2空不空{while (!tstq->S1.empty())//当栈1空了就停 直到将栈1数据全部导完{//将S1中的数据放到S2中 下面是只放一个数据的操作ELEMTYPE tmp = tstq->S1.top();tstq->S1.pop();tstq->S2.push(tmp);}}printf("%c\n", tstq->S2.top());tstq->S2.pop();return true;
}//1.用两个栈来模拟实现一个队列//测试用例
int main()
{TwoStack_toQueue head;Push_TSTQ(&head, 'A');Push_TSTQ(&head, 'B');Push_TSTQ(&head, 'C');Pop_TSTQ(&head);//APush_TSTQ(&head, 'D');Push_TSTQ(&head, 'E');Pop_TSTQ(&head);//BPop_TSTQ(&head);//CPop_TSTQ(&head);//DPop_TSTQ(&head);//Ereturn 0;
}
2.怎么用两个栈来模拟实现一个队列
//2.用两个队列来模拟实现一个栈
//入栈
bool Push_TQTS(TwoQueue_toStack* tqts, ELEMTYPE ch)
{tqts->Q1.push(ch);return true;
}
//出栈
bool Pop_TQTS(TwoQueue_toStack* tqts)
{if (tqts->Q1.empty() && tqts->Q2.empty())return false;if (!tqts->Q1.empty()){int size = (int)tqts->Q1.size();//3 ABCfor (int i = 0; i < size - 1; i++)//{ELEMTYPE tmp = tqts->Q1.front();tqts->Q1.pop();tqts->Q2.push(tmp);}printf("%c\n", tqts->Q1.front());tqts->Q1.pop();return true;}else{int size = (int)tqts->Q2.size();for (int i = 0; i < size - 1; i++)//{ELEMTYPE tmp = tqts->Q2.front();tqts->Q2.pop();tqts->Q1.push(tmp);}printf("%c\n", tqts->Q2.front());tqts->Q2.pop();return true;}}
//模拟实现 获取栈顶元素值这个函数 特别注意一下
//2.用两个队列来模拟实现一个栈//测试用例
int main()
{TwoQueue_toStack head;Push_TQTS(&head, 'A');//APush_TQTS(&head, 'B');//ABPush_TQTS(&head, 'C');//ABCPop_TQTS(&head); //ABC->ABPush_TQTS(&head, 'D'); //ABDPush_TQTS(&head, 'E'); //ABDEPop_TQTS(&head);//ABDE->ABDPop_TQTS(&head);//ABD->AB}