![](/img/trans.png)
[英]Trying to get rid of repeated indexes in my stack push function. I am using a 2d array to simulate a linked list
[英]I am trying to implement a stack using two Queues but my "push" operation is problematic although the code seems to be fine
這是 class“StackUsingTwoQueues”的代碼
Class“queueUsingLL”工作正常,以下是用於此 class 的方法
使用這個隊列 class 我試圖實現堆棧
class StackUsingTwoQueues {
QueueUsingLL<int> q;
QueueUsingLL<int> tempQ;
public:
bool isEmpty(){
return q.isEmpty();
}
int pop(){
if(isEmpty()){
return -1;
}
else{
return q.dequeue();
}
}
int size(){
return q.size();
}
// following push method is problematic : -
void push(int element){
if(q.isEmpty()){
q.enqueue(element);
}
else{
for(int i = 0; i < q.size(); i++){
tempQ.enqueue(q.dequeue());
}
q.enqueue(element);
for(int i = 0; i < tempQ.size(); i++){
q.enqueue(tempQ.dequeue());
}
}
}
int top(){
return q.front();
}
};
請注意,如果我為 push() function 編寫以下代碼,它可以正常工作:-
void push(int element){
while(!q.isEmpty()){
tempQ.enqueue(q.dequeue());
}
q.enqueue(element);
while(!tempQ.isEmpty()){
q.enqueue(tempQ.dequeue());
}
}
這是司機 function:-
Output 預計:1 2 3 4 5
實際 Output:1 2 1 2 1
int main(){
int arr[] = {1,2,3,4,5};
StackUsingTwoQueues s;
for(int i = 0; i < 5; i++){
s.push(arr[i]);
cout<<s.top()<<" ";
}cout<<endl;
}
給出了此任務的條件。 應使用 2 個隊列。
問題是您在for
循環中使用變量值作為結束條件。 您使用size()
function,初始值正確。 但是隨后您從隊列中彈出元素,然后size
將減少一個。
這在邏輯上是行不通的。
而不是這樣:請將size()
分配給另一個變量,就在循環之前。 然后使用這個循環不變值作為循環的結束條件。 對兩個循環執行此操作。
您的 function 的 rest 完全沒問題。
請在下面查看您更正后的代碼:
#include <iostream>
#include <list>
template <class T>
class QueueUsingLL {
std::list<T> data{};
public:
bool isEmpty() const { return data.empty(); }
std::size_t size() const { return data.size(); }
void enqueue(const T& value) { data.push_back(value); }
T dequeue() { T value{ data.front() }; data.pop_front(); return value; }
T front() { return data.front(); };
};
class StackUsingTwoQueues {
QueueUsingLL<int> q;
QueueUsingLL<int> tempQ;
public:
bool isEmpty() {
return q.isEmpty();
}
int pop() {
if (isEmpty()) {
return -1;
}
else {
return q.dequeue();
}
}
int size() {
return q.size();
}
// following push method is problematic : -
void push(int element) {
if (q.isEmpty()) {
q.enqueue(element);
}
else {
std::size_t numberOfElements{ q.size() };
for (std::size_t i = 0; i < numberOfElements; i++) {
tempQ.enqueue(q.dequeue());
}
q.enqueue(element);
numberOfElements = tempQ.size() ;
for (int i = 0; i < numberOfElements; i++) {
q.enqueue(tempQ.dequeue());
}
}
}
int top() {
return q.front();
}
};
int main() {
int arr[] = { 1,2,3,4,5 };
StackUsingTwoQueues s;
for (int i = 0; i < 5; i++) {
s.push(arr[i]);
std::cout << s.top() << " ";
}
std::cout << '\n';
while (s.size())
std::cout << s.pop() << ' ';
}
我為您的隊列創建了一個存根 class。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.