链表实现队列出队和入队
程序员文章站
2024-03-24 23:58:10
...
队列需要两个链表结点来表示头和尾,入队可视为从队尾的链表结点插入一个新的结点,插入后需要将队尾指针后移,而出队则是查询队首结点的值,将队首指针后移,并将队首指针所指向的内存区域释放。
#include<iostream>
#include<stdio.h>
using namespace std;
typedef struct listnode{
int data;
listnode * next;
}node;
typedef struct linkqueue
{
node * first=NULL, *rear=NULL;
}queue;
queue * enqueue(queue * q, int x)
{
node * p = (node *)malloc(sizeof(node));
p->data = x;
p->next = nullptr;
if (q->rear == NULL)
{
q->rear = p;
q->first = p;
}
else
{
q->rear->next = p;
q->rear = p;
}
return q;
}
int popqueue(queue * q)
{
if (q->first == NULL)
cout << "队列溢出" << endl;
else
{
node * p = q->first;
int temp = p->data;
q->first = p->next;
free(p);
return temp;
}
}
void printqueue(queue * q)
{
node *p = q->first;
while (p!= NULL)
{
cout << p->data <<" ";
p = p->next;
}
cout << endl;
}
int main(){
queue q;
enqueue(&q , 3);
enqueue(&q, 5);
enqueue(&q, 8);
printqueue(&q);
popqueue(&q);
printqueue(&q);
popqueue(&q);
printqueue(&q);
popqueue(&q);
printqueue(&q);
popqueue(&q);
printqueue(&q);
system("pause");
return 0;
}