C++队列实现及优化:从数组到类的演进
C++队列实现及优化:从数组到类的演进
本文将探讨如何使用C++实现队列数据结构,从基础的数组实现到更优化的类封装,并提供代码示例和优化技巧。
1. 基于数组的队列实现
以下是一个使用C++数组实现队列的示例代码:c++#include<bits/stdc++.h>using namespace std;
const int N=100000;
int qu[N];int head=1;int tail=0;
void push(int x) { qu[++tail]=x;
}
void pop() { if(tail>=head) head++; else cout<<'FBI WARNING ';
}
bool empty() { if(tail>=head) return false; else return true;
}
int query() { if(tail>=head) return qu[head]; else cout<<'FBI WARNING '; return -1;}
int main() {
int n; cin>>n; string str; int x; while(n--) { cin>>str;
if(str=='push') { cin>>x; push(x);
} else if(str=='pop') { pop();
} else if(str=='empty') { if(empty()) cout<<'YES
'; else cout<<'NO ';
} else { cout<<query()<<'
';
}
}
return 0;}
这段代码实现了队列的基本操作,如入队 (push),出队 (pop),判断队列是否为空 (empty) 以及获取队首元素 (query)。
2. 基于类的队列实现
为了更好地封装数据结构和提高代码可读性,我们可以使用类来实现队列。以下是用 Python 实现的队列类:pythonclass Queue: def init(self): self.queue = []
def push(self, x): self.queue.append(x) def pop(self): if not self.empty(): self.queue.pop(0) else: print('FBI WARNING')
def empty(self): return len(self.queue) == 0 def query(self): if not self.empty(): return self.queue[0] else: print('FBI WARNING') return -1
if name == 'main': n = int(input()) queue = Queue()
while n > 0: operation = input().split()
if operation[0] == 'push': queue.push(int(operation[1])) elif operation[0] == 'pop': queue.pop() elif operation[0] == 'empty': if queue.empty(): print('YES') else: print('NO') elif operation[0] == 'query': front = queue.query() if front != -1: print(front)
n -= 1
在这段代码中,我们将队列的实现封装在一个名为 Queue 的类中。这样做的好处是可以将队列的数据和操作封装在一起,提高代码的可读性和可维护性。
3. 总结
本文介绍了两种使用 C++ 实现队列的方法:基于数组和基于类。基于类的实现更易于理解和维护,并且可以更好地封装数据结构。在实际应用中,我们应该根据具体需求选择合适的实现方式。
希望本文对你有所帮助!如有任何问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/crol 著作权归作者所有。请勿转载和采集!