队列的链式存储
代码如下:
- #include
- #include
-
- typedef struct Node
- {
- int data;
- struct Node *next;
- }Node;
-
- typedef struct
- {
- Node *front;
- Node *rear;
- }LinkQueue;
-
- void InitQueue1(LinkQueue &Q)//带头结点
- {
- Q.front=Q.rear=(Node*)malloc(sizeof(Node));
- Q.front->next=NULL;
- }
-
- void InitQueue2(LinkQueue &Q)//不带头结点
- {
- Q.front=Q.rear=NULL;
- }
-
- bool IsEmpty(LinkQueue Q)
- {
- if(Q.front==Q.rear) return true;
- else return false;
- }
-
- void Push1(LinkQueue &Q,int x)//不带头结点
- {
- Node *q=(Node*)malloc(sizeof(Node));
- q->data=x;
- q->next=NULL;
-
- Q.rear->next=q;
- Q.rear=q;
- }
-
- void Push2(LinkQueue &Q,int x)//带头结点
- {
- Node *q=(Node*)malloc(sizeof(Node));
- q->data=x;
- q->next=NULL;
-
- if(Q.front==NULL)//不带头结点,第一个元素入队列
- {
- Q.front=q;
- Q.rear=q;
- }
- else
- {
- Q.rear->next=q;
- Q.rear=q;
- }
- }
-
- void Pop(LinkQueue &Q,int &x)//带头结点
- {
- if(Q.front==Q.rear)
- {
- printf("队列为空");
- }
- x=Q.front->next->data;
- Q.front->next=Q.front->next->next;
- }
-
- int main()
- {
- LinkQueue Q;
- InitQueue1(Q);
-
- //InitQueue2(Q);
-
- printf("%d\n",IsEmpty(Q));
-
- Push(Q,150);
- Push(Q,500);
- Push(Q,985);
-
- int x;
- Pop(Q,x);
- printf("当前出队的队首元素为%d\n",x);
- Pop(Q,x);
- printf("当前出队的队首元素为%d\n",x);
- Pop(Q,x);
- printf("当前出队的队首元素为%d\n",x);
-
- GetTop();
- GetTail();
-
- return 0;
- }