#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct Node{
int data;
struct Node* next;
}Node;
void push(Node *&front,Node *&rear,int x){//输入队首指针,队尾指针,值X
Node *tmp=(Node*)malloc(sizeof(Node));//开临临时结点
tmp->data=x;//赋值
tmp->next=NULL;//赋后继
if(rear!=NULL){//当前队列非空
rear->next=tmp;//则更新尾针后继
rear=tmp;//然后尾针再变为其后继
}//最后这句就是rear=rear->next;这样或许好理解些
else{//空队的判断条件是rear==NULL或front=NULL
rear=tmp;//尾指针变为其后继
front=tmp;//全局关键就在这里!!!
}//考研书的模板里链队是没有头结点的!
}
int pop(Node *&front){//输入队首结点
if(front==NULL)return 0;//空队返0删除失败
Node *tmp=front;//读出队首结点(其实就是为了后面释放空间)
front=front->next;//队首变为后继
free(tmp);//释放结点空间
return 1;//返1删除成功
}
int main(){//链队列
Node* front=NULL,*rear=NULL;//定义首尾指针,不用申请空间
push(front,rear,100);push(front,rear,200);push(front,rear,300);//入队三连
cout<<front->data<<' '<<rear->data<<endl;pop(front);//读出首尾结点值并弹出队首结点
cout<<front->data<<' '<<rear->data<<endl;pop(front);//读出首尾结点值并弹出队首结点
cout<<front->data<<' '<<rear->data<<endl;pop(front);//读出首尾结点值并弹出队首结点
return 0;
}
/***output
100 300
200 300
300 300
***/
1基础-6链队列
最新推荐文章于 2023-09-05 15:00:00 发布