队列的特征就是“先入先出”,入队时在链表的尾部插入数据,出队时删除掉头节点后面的节点,需要一个尾指针,始终指向链表的尾部(新加进来的节点)。具体请看原理图:
代码实现
#include <stdio.h>
#include <stdlib.h>typedef struct List
{int data; //数据域struct List *next; //指针域
}ListNode; //节点信息ListNode *rear; //尾指针void Init(ListNode *head); //队列初始化
void push(ListNode *head, int data); //入队
void pop(ListNode *head); //出队
void print(ListNode *head); //显示队内元素int main()
{ListNode head;Init(&head);push(&head, 1);print(&head);pop(&head);print(&head);pop(&head);print(&head);system("pause");return 0;
}void Init(ListNode *head)
{head->data = 0;head->next = head;rear = head; //尾指针指向头节点
}void push(ListNode *head,int data)
{ListNode *tem = (ListNode *)malloc(sizeof(ListNode));if (tem == NULL){printf("创建新节点失败,入队失败");return;}rear->next = tem; //尾指针指向的节点的指针指向新节点tem->data = data;tem->next = head; //尾结点指向头,实现循环rear = tem; //尾指针后移
}void pop(ListNode *head)
{if (head ->next == head){printf("队内无元素,出队错误\n");return;}ListNode *tem = head->next;head->next = tem->next; //头节点指向下下个节点printf("出队元素: %d\n", tem->data);if (tem->next == head){rear = head; //删除到最后一个元素时,尾指针指向头节点}free(tem);tem=NULL;
}void print(ListNode *head)
{ListNode *tem = head->next;if (tem == head){printf("当前队列无元素\n");return;}for (; tem != head; tem = tem->next){printf("%d ", tem->data);}printf("\n");
}