[英]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.