元素一个一个进入队列中,最先进入的最先出来,如同排队买火车票,先进的先出
a.头文件 queuelisth.h
- C/C++ code
- typedef struct NODE { struct NODE *link; char *name; }Node; /** * 创建新节点 */ Node* create_node(); /** * 打印节点所带数据 */ void printf_node(Node *head); /** * 进入队列 */ void inqueue(char *name); /** * 出队列 */ void outqueue(); /** * 队列是否为空 */ int is_empty();
b. 具体实现 queuelist.c
- C/C++ code
- /** * author:srgzyq * email:srgzyq@gmail.com */ #include "queuelisth.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #define NAME_LEN 10 static Node *head; Node* create_node() { Node *new = (Node *)malloc(sizeof(Node)); if(new == NULL) return new; char *name = (char *)calloc(NAME_LEN,sizeof(char)); if(!name) { free((Node *)new); return NULL; } new->name = name; return new; } void printf_node(Node *node) { printf("queue: %s\n",node->name); } void inqueue(char *name) { Node *new = create_node(); new->name = name; /** * 队列为空 当前节点为头节点 */ if(head == NULL) { head = new; printf("frist : %s\n",head->name); return; } Node *frist = head; while(head->link != NULL) head = head->link; /** * 放入到队尾 */ head->link = new; head = frist; printf("in queue %s\n",name); } void outqueue() { Node *curNode = head; printf_node(curNode); head = head->link; free(curNode); } int is_empty() { return head == NULL; }
c.测试代码 queuelisttest.c
- C/C++ code
- #include <stdio.h> #include <stdlib.h> #include <string.h> #define ARR_LEN 5 char data_arr[][10] = {"wangbo","raodie","niba","bobo","pengdui"}; int main() { int index; for(index = 0;index < ARR_LEN; index++) inqueue(data_arr[index]); while(!is_empty()) outqueue(); return EXIT_SUCCESS; }
编译输出:
gcc -o2 -o queuelisttest queuelist.c queuelisttest.c
./queuelisttest
frist : wangbo
in queue raodie
in queue niba
in queue bobo
in queue pengdui
queue: wangbo
queue: raodie
queue: niba
queue: bobo
queue: pengdui