7 兩個棧模擬佇列,兩個佇列模擬棧

2021-06-28 04:26:45 字數 1338 閱讀 5492

利用兩個棧模擬佇列

stack1,stack2

首先向stack1當中放入資料,如果需要輸出資料,從stack2中delete資料,如果stack2為空,就把stack1中資料匯入stack2

#include "static.h"

#include #include templateclass cquue

; ~cquue(){};

t deletehead();

private:

stackm_stack1;

stackm_stack2; //《存入資料的時候放入到stack1當中,取資料從stack2中取出,如果stack2為空,將stack1中資料轉入stack2當中

};templatet cquue::deletehead()

while(!m_stack1.empty())

}t valuetemp = m_stack2.top();

m_stack2.pop();

printf("%d ",valuetemp);

return valuetemp;

}int main()

兩個佇列模擬棧

這裡用的方法和書中提到的方法不太一樣,但是大致意思都是相同的,但是書中的方法會減少判斷語句

兩個佇列,每次放入資料將資料放入乙個空的佇列當中,同時將另乙個佇列中的資料copy到當前這個佇列當中,又保持乙個空佇列

輸出資料的時候就從非空佇列中輸出

但是這樣的方法每輸入乙個資料就需要copy一次,也比較麻煩

在書中,是每一次輸出資料的時候需要將前面的資料copy到另乙個queue當中

#include "static.h"

#include #include templateclass cstack

; ~cstack(){};

t deletehead();

private:

queuem_queue1;

queuem_queue2; //《存入資料的時候放入到m_queue1當中,然後再將資料都匯入進queue2當中,然後每次新增資料放入乙個空的queue當中

}; }

else }

}templatet cstack::deletehead()

if (m_queue1.size()>0)

else

printf("%d ",tempvalue);

return tempvalue;

}int main()

兩個棧模擬佇列

演算法導論上的課後題 兩個棧模擬佇列 這個原來做過 一般是這樣 我看網上大概都是這種解法 原來棧空 a b null null 1,2,3入站的時候入a a b 3 null 2 null 1 null 出戰的時候先進b 然後pop b 在調過來進a a b null 1 null 2 null 3...

兩個棧模擬乙個佇列 兩個佇列模擬乙個棧

解題思路 插入操作在stack1中進行,刪除操作在stack2中進行,如果stack2為空,則將stack1中的所有元素轉移到stack2中。include include includeusing namespace std template class cqueue 建構函式 template ...

兩個棧來模擬佇列

用兩個棧來模擬佇列,注意,當pop元素之後,不需要把元素重新恢復成原來的位置。寫了好久的c 今天終於嘗試到用template來寫類了,感覺不錯。include include templateclass queue queue 插入元素 void push datatype data 刪除元素 vo...