数据结构-使用两个栈实现一个队列
生活随笔
收集整理的這篇文章主要介紹了
数据结构-使用两个栈实现一个队列
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1:如何只使用stack實(shí)現(xiàn)queue呢?我們知道stack是先進(jìn)后出的(FIFO),而queue是先進(jìn)先出的(FIFO)。也就是說,stack進(jìn)行了一次反向。如果進(jìn)行兩次反向,就能實(shí)現(xiàn)queue的功能,所以我們需要兩個stack實(shí)現(xiàn)queue。
? ? 下面是具體思路。
假設(shè)有兩個棧A和B,且都為空。可以認(rèn)為棧A為提供入隊(duì)列的功能,棧B提供出隊(duì)列的功能。
(1)如果棧B不為空,直接彈出棧B的數(shù)據(jù)。
(2)如果棧B為空,則依次彈出棧A的數(shù)據(jù),放入到棧B中,再彈出棧B的數(shù)據(jù)。
代碼如下:
#include "stdafx.h" #include<malloc.h> #include <iostream> #include <assert.h> using namespace std;/*單鏈表的節(jié)點(diǎn),data表示節(jié)點(diǎn)的數(shù)據(jù)域,next指向下一個節(jié)點(diǎn)*/ class MyData { public:MyData() :data(0), next(NULL) {};//默認(rèn)構(gòu)造函數(shù),這樣表示后,主體中不用再寫這個函數(shù)了MyData(int value) :data(value), next(NULL) {};//帶參數(shù)的構(gòu)造函數(shù)int data;//數(shù)據(jù)域MyData *next;//下一個節(jié)點(diǎn) };/*表示棧的定義,其中public成員top表示棧頂,由于不能直接操作棧底,因此這里沒有定義棧底的指針。 在默認(rèn)構(gòu)造函數(shù)中,把棧頂指針top置空,表示此時棧為空棧。*/ class MyStack { public:MyStack() :top(NULL) {};//默認(rèn)構(gòu)造函數(shù)void push(MyData data);//進(jìn)棧void pop(MyData *pData);//出棧bool IsEmpty();//是否為空棧MyData *top;//棧頂 };class MyQueue { public:void enqueue(MyData data);//入隊(duì)void dequeue(MyData &data);//出隊(duì)bool IsEmpty();//是否為空隊(duì) private:MyStack s1;//用于入隊(duì)MyStack s2;//用于出隊(duì) };//進(jìn)棧 void MyStack::push(MyData data) {MyData *pData = NULL;pData = new MyData(data.data);//生成新節(jié)點(diǎn)pData->next = top;top = pData; }//判斷棧是否為空 bool MyStack::IsEmpty() {return(top == NULL);//如果top為空,則返回1,否則返回0 }//出棧 void MyStack::pop(MyData *data)//將刪除的節(jié)點(diǎn)保存到data中 {if (IsEmpty())//如果棧為空,直接返回 {return;}data->data = top->data;//給傳出的參數(shù)賦值MyData *p = top;//臨時保存原棧頂節(jié)點(diǎn)top = top->next;//移動棧頂,指向下一個節(jié)點(diǎn)delete p;//釋放原棧頂節(jié)點(diǎn)內(nèi)存 }//入隊(duì) void MyQueue::enqueue(MyData data) {s1.push(data);//只對s1進(jìn)行操作 }//出隊(duì) void MyQueue::dequeue(MyData &data) {MyData temp(0);//局部變量,用于臨時存儲if (s2.IsEmpty()){while (!s1.IsEmpty())//如果s2為空,把s1的所有元素push到s2中 {s1.pop(&temp);//彈出s1的元素s2.push(temp);//壓入s2中 }}if (!s2.IsEmpty()){s2.pop(&data);//此時s2不為空,則彈出s2的棧頂元素 } }//隊(duì)列判空 bool MyQueue::IsEmpty() {//如果兩個棧都為空,則返回1,否則返回0return(s1.IsEmpty() && s2.IsEmpty()); } int main() {MyData data(0);//定義一個節(jié)點(diǎn) MyQueue q;q.enqueue(MyData(1));q.enqueue(MyData(2));q.enqueue(MyData(3));q.dequeue(data);cout << "dequeue" << data.data << endl;q.dequeue(data);cout << "dequeue" << data.data << endl;q.dequeue(data);cout << "dequeue" << data.data << endl;cout << "IsEmpty:" << q.IsEmpty() << endl;return 0; } View Code運(yùn)行結(jié)果:
轉(zhuǎn)載于:https://www.cnblogs.com/lovemi93/p/7607203.html
總結(jié)
以上是生活随笔為你收集整理的数据结构-使用两个栈实现一个队列的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pythonllk
- 下一篇: 关于h5中背景音乐的自动播放