首页 > 代码库 > 链式队列实现
链式队列实现
三个文件:main.c student.c student.h
student.h文件如下:
#ifndef STUDENT_H_#define STUDENT_H_#include<stdio.h>#include<string.h>#include<malloc.h>#include<stdlib.h>#define CMD_ADD_NODE ‘1‘#define CMD_DEL_NODE ‘2‘#define CMD_SHOW_NODE ‘3‘#define CMD_QUIT_NODE ‘4‘ #define MAX 10typedef struct{ char name[20]; int grade;}Item;typedef struct node{ Item item; struct node *next;}Node;typedef struct{ Node *front; /* 队头指针 */ Node *rear; /* 队尾指针 */ int items;}Queue;static inline void print(const Item item){ printf("%s, %d\n", item.name, item.grade); return ;}int QueueAdd( Queue *queue,Item item);int QueueDel(Queue *queue, Item *item);int QueueShow(const Queue *queue);#endif
main.c文件如下:
#include"student.h"int main(int argc, char **argv){ char cmd = 0; Queue queue={NULL,NULL,0}; Item item; //Initialize(&queue); while(1) { printf("The Menun Is:\n"); printf("1.add\n"); printf("2.delete\n"); printf("3.show\n"); printf("4.quit\n"); printf("Enter your choice(1~4):"); cmd = getchar(); while( (getchar()) != ‘\n‘ ) continue;//跳过输入行的多余部分 while( cmd != CMD_ADD_NODE && cmd != CMD_DEL_NODE && cmd != CMD_SHOW_NODE && cmd != CMD_QUIT_NODE) { printf("Please input 1~4:"); cmd = getchar(); while( (getchar()) != ‘\n‘ ) continue;//跳过输入行的多余部分 } switch(cmd) { case CMD_ADD_NODE : printf("Enter name and grade:"); scanf("%s%d",item.name,&(item.grade)); while( (getchar()) != ‘\n‘ ) continue;//跳过输入行的多余部分 QueueAdd(&queue, item); break; case CMD_DEL_NODE : QueueDel(&queue, &item); printf("Delete:"); print(item); break; case CMD_SHOW_NODE : QueueShow(&queue); break; case CMD_QUIT_NODE : exit(0); break; default: break; } printf("\n"); } return 0;}
student.c文件如下:
#include "student.h"static int QueueIsEmpty(const Queue *queue){ return (queue->items == 0);}static int QueueIsFull(const Queue *queue){ return (queue->items == MAX);}/* 插到队尾 */int QueueAdd(Queue *queue, Item item){ Node *node; if( QueueIsFull(queue) ) { fprintf(stderr,"The queue is full!!!\n"); return -1; } node = (Node *)malloc(sizeof(Node)); if(node == NULL) { fprintf(stderr, "Cannot creat a node!!!\n"); return -1; } node->item = item; node->next = NULL; if( QueueIsEmpty(queue) ) { queue->front = node; } else { queue->rear->next = node; } queue->rear = node; queue->items ++; return 0;}/* 在队头删除 */int QueueDel( Queue *queue, Item *item ){ Node *node; if( QueueIsEmpty(queue) ) { fprintf(stderr, "The queue is empty!!!\n"); return -1; } *item = queue->front->item; node = queue->front; queue->front = node->next; queue->items --; free(node); return 0;}int QueueShow( const Queue *queue ){ int i; Node *node = queue->front; if( QueueIsEmpty(queue) ) { fprintf(stderr, "The queue is empty!!!\n"); return -1; } printf("All of the student:\n"); for( i=0; i<(queue->items); i++ ) { print(node->item); node = node->next; } printf("\n"); return 0;}
链式队列实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。