#include <iostream>
using namespace std;
typedef struct _node{
int data;
struct _node* next;
_node(int e ,struct _node* p = nullptr){
data = e;
next = p;
}
}node;
class queue{
public:
queue():m_start(new node(-1,nullptr)),m_tail(m_start),m_length(0){}
~queue(){
while(m_start->next != nullptr){
node* pdel = m_start;
m_start = m_start->next;
delete pdel;
}
m_start = m_tail = nullptr;
}
void push(int e);
void pop();
int front();
int back();
bool isEmpty();
int size();
private:
node* m_start;
node* m_tail;
int m_length;
};
void queue::push(int e){
node* pnew = new node(e,nullptr);
m_tail->next = pnew;
m_tail = pnew;
++m_length;
}
void queue::pop(){
if(m_start->next == nullptr){
cout << "queue is empty.\n";
}else{
node* pdel = m_start->next;
m_start->next = pdel->next;
delete pdel;
--m_length;
if (m_length == 0){
m_tail = m_start;
}
}
}
int queue::front(){
if(m_tail == m_start){
cout << "queue is empty.\n";
exit(1);
}else{
return m_start->next->data;
}
}
int queue::back(){
if(m_tail == m_start){
cout << "queue is empty.\n";
exit(1);
}else{
return m_tail->data;
}
}
bool queue::isEmpty(){
return m_tail == m_start;
}
int queue::size(){
return m_length;
}
int main(){
queue q;
for (int i = 0; i < 10; ++i){
q.push(i);
}
cout << "queue first is: " << q.front() << endl;
cout << "queue last is: " << q.back() << endl;
for (int i = 0; i < 10; ++i){
cout << "queue first is: " << q.front() << ends << "queue size is: " << q.size() << endl;
q.pop();
}
cout << "queue is empty: " << q.isEmpty() << endl;
for (int i = 0; i < 10; ++i){
q.push(i);
}
cout << "queue first is: " << q.front() << endl;
cout << "queue last is: " << q.back() << endl;
return 0;
}
queue链表实现C++
最新推荐文章于 2024-06-20 19:08:43 发布