链式队列
链式队列和链表很相似。
不过对链式队列中数据的添加是通过两个指针进行top和rear(添加和输出都是one by one)
对于链式队列有两种基本方式,一种是带有头结点,一种是没有头结点。没有头结点的方式,需要自己去获取第一次添加元素的队头。
推荐有头结点的方式,方便理解。
含有头结点方式:
#include <iostream> #include <vector> using namespace std; struct Queue { int ele; Queue *next; }; Queue *InitQueue() { Queue *q = new Queue; q->ele = NULL; q->next = NULL; return q; } Queue *enQueue(Queue *rear, int ele) { Queue *list = new Queue; list->ele = ele; list->next = NULL; rear->next = list; rear = rear->next; return rear; } Queue* deQueue(Queue *top, Queue *rear) { if (top->next == NULL) { cout << "队列为空!" << endl; return top; } top = top->next; cout << top->ele << endl; return top; } int main() { Queue *top, *rear; top = rear = InitQueue(); rear = enQueue(rear, 5); rear = enQueue(rear, 10); top = deQueue(top, rear); top = deQueue(top, rear); top = deQueue(top, rear); system("PAUSE"); return 0; }
不含有头结点的方式;
#include <iostream> #include <vector> using namespace std; struct Queue { int ele; Queue *next; }; Queue *InitQueue() { Queue *q = new Queue; q->ele = NULL; q->next = NULL; return q; } Queue *enQueue(Queue *rear, int ele) { if (rear == NULL) { rear = new Queue; rear->ele = ele; rear->next = NULL; } else { Queue *list = new Queue; list->ele = ele; list->next = NULL; rear->next = list; rear = rear->next; } return rear; } Queue* deQueue(Queue *top, Queue *rear) { if (top == NULL) { cout << "队列为空!" << endl; return top; } cout << top->ele << endl; top = top->next; return top; } int main() { Queue *top, *rear; top = rear = NULL; top = rear = enQueue(rear, 5); rear = enQueue(rear, 10); top = deQueue(top, rear); top = deQueue(top, rear); top = deQueue(top, rear); system("PAUSE"); return 0; }