链队列

1. #include <stdio.h>  

2. #include <stdlib.h>  

3. #define Datatype int  

4. //定义节点结构  

5. typedef struct node{  

6.     Datatype data;  

7.     struct node *next;  

8. }QueueNode;  

9. //定义头节点  

10. typedef struct{  

11.     QueueNode *front;  

12.     QueueNode *rear;  

13. }LinkQueue;  

14.   

15. //初始化链队列,头节点置空  

16. void InitQueue(LinkQueue *Q)  

17. {  

18.     Q->front = Q->rear = NULL;  

19. }  

20.   

21. //判断链队列是否为空  

22. int QueueEmpty(LinkQueue *Q)  

23. {  

24.     return(Q->front == NULL && Q->rear == NULL);  

25. }  

26.   

27. //入队  

28. void EnLinkQueue(LinkQueue *Q, Datatype v)  

29. {  

30.     QueueNode *p;  

31.     p = (QueueNode *)malloc(sizeof(QueueNode));//为新的节点分配空间  

32.     p->data = v;  

33.     p->next = NULL;  

34.     if(QueueEmpty(Q))  

35.         Q->front = Q->rear = p;  

36.     else  

37.     {  

38.         Q->rear->next = p;  //将新的节点连接到队列  

39.         Q->rear = p;             //指向队列尾  

40.     }  

41. }  

42.   

43. //出队  

44. Datatype DeLinkQueue(LinkQueue *Q)  

45. {  

46.     Datatype i;  

47.     QueueNode *s;  

48.     if(QueueEmpty(Q))     //判断队列是否为空  

49.         printf("Error,the linkqueue is empty!");  

50.     s = Q->front;  

51.     i = s->data;  

52.     if(Q->front == Q->rear)   //判断队列是否只有一个节点  

53.         Q->front = Q->rear = NULL;  

54.     else  

55.         Q->front = s->next;  

56.     free(s);  

57.     return i;  

58.   

59. }  

60.   

61. //读取队列头元素,不改变队列状态  

62. Datatype ReadLinkQueue(LinkQueue *Q)  

63. {  

64.     Datatype i;  

65.     if(QueueEmpty(Q))     //判断队列是否为空  

66.         printf("Error,the linkqueue is empty!");  

67.     i = Q->front->data;  

68.     return i;  

69. }  

70.   

71. int main()  

72. {  

73.     LinkQueue Q;  

74.     Datatype i = 1;  

75.     InitQueue(&Q);  

76.     while(i<=6)  

77.     {  

78.         EnLinkQueue(&Q,i);      //将1-6入队  

79.         i++;  

80.     }  

81.     printf("DeLinkQueue: %d\n", DeLinkQueue(&Q));  

82.     printf("DeLinkQueue: %d\n", DeLinkQueue(&Q));  

83.     printf("ReadLinkQueue: %d\n", ReadLinkQueue(&Q));  

84.     printf("ReadLinkQueue: %d\n", ReadLinkQueue(&Q));  

85.   

86.     EnLinkQueue(&Q,9);  

87.     printf("The all number of the linkqueue:\n");  

88.     while(!QueueEmpty(&Q))  

89.         printf("%d\t",DeLinkQueue(&Q));         //输出队列中所有数据  

90.   

91.     return 0;  

92. }  

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值