数据结构基础(二)队列的实现

来源:互联网 发布:注册码万能破解软件 编辑:程序博客网 时间:2024/04/29 05:15

使用链表实现的队列:

typedef struct queueNode{int val;queueNode* next;}Node;class queue{public:queue(){front=NULL;back=NULL;};bool empty(){if (front==NULL||back==NULL){return true;}return false;};void push(int data){//在链表尾巴上插入 从尾巴入队if (empty()){front=new Node;front->val=data;back=front;back->next=NULL;return ;}back->next=new Node;back=back->next;back->val=data;back->next=NULL;return ;};bool pop(int& data){  //从将尾巴的移到前一个if (empty()){return false;}if (back==front){data=front->val;delete front;back=NULL;front=NULL;return true;}data=front->val;Node* temp=front;Node* pre=NULL;while (temp->next!=NULL){pre=temp;temp->val=temp->next->val;temp=temp->next;}//temp代表尾节点//delete temp 并且上个节点的next要设为NULLdelete temp;pre->next=NULL;back=pre;return true;};void print(){if (empty()){return;}Node *temp=front;while(temp->next!=NULL){cout<<temp->val<<"\t";temp=temp->next;}cout<<temp->val<<"\t";};void clear(){// //释放链表内存// if (empty())// {// return;// }// // Node *temp=front;// Node *pre=NULL;// while(temp->next!=NULL)// {// pre=temp;// temp=temp->next;// delete pre;// }// delete temp;// temp=NULL;// front=back=NULL;int temp;while(!empty()){pop(temp);}};private:Node *front;Node *back;};

0 0
原创粉丝点击