zoukankan      html  css  js  c++  java
  • C语言队列的实现

    对于C语言的队列来说,也有顺序存储和链表存储两种方式。

    顺序存储容量固定,链表存储随时分配释放更加灵活。

    下面是链表实现的队列初始化、入队、出队函数实现:

    #include<stdio.h>
    #include <malloc.h>
    #include <stdlib.h>
    
    typedef struct Node
    {
    	int val;
    	struct Node* next;
    }NODE, * PNODE;
    
    typedef struct Queue
    {
    	PNODE front, rear;
    }QUEUE, *PQUEUE;
    
    void InitQueue(PQUEUE queue)
    {
    	queue->front = queue->rear = (PNODE)malloc(sizeof(NODE));
    	if (queue->front == NULL)
    	{
    		printf("没有足够内存空间,错误
    ");
    	}
    	queue->front->next = NULL;
    }
    
    void InsertQueue(PQUEUE queue, int val)
    {
    	PNODE tmp = (PNODE)malloc(sizeof(NODE));
    	if (tmp == NULL)
    	{
    		printf("无足够内存空间,错误
    ");
    	}
    	tmp->val = val;
    	tmp->next = NULL;
    	queue->rear->next = tmp;
    	queue->rear = queue->rear->next;
    	tmp = NULL;
    }
    
    int DeleteQueue(PQUEUE queue)
    {
    	if (queue->front == queue->rear)
    	{
    		printf("队列为空
    ");
    	}
    	PNODE p = NULL;
    	int val;
    	p = queue->front->next;
    	queue->front->next = p->next;
    	val = p->val;
    	free(p);
    	p = NULL;
    	return val;
    
    }
    
    int main(void)
    {
    	QUEUE queue;
    	InitQueue(&queue);
    	InsertQueue(&queue, 1);
    	InsertQueue(&queue, 2);
    	InsertQueue(&queue, 3);
    	for (int i = 0; i < 3; i++)
    		printf("%d
    ", DeleteQueue(&queue));
    
    	return 0;
    }
    

      

    注意:在定义队列的时候,不能定义PQUEUE,因为他是一个指针,在定义时需要指向NULL,但是指向NULL的指针是不允许对内部的结点进行任何操作的,因此需要定义QUEUE。

    再通过&queue将队列指针传递进去。

  • 相关阅读:
    JS控制台打印星星,总有你要的那一款~
    css居中方法
    line-height
    position定位
    IE盒子模型
    CSS中的盒模型
    CSS中的BEM命名
    循环语句总结(代码以C#为例)
    程序设计中的数学思维函数总结(代码以C#为例)
    转:SpringBoot 自定义异常@ContollerAdvice ExceptionHandler不起作用
  • 原文地址:https://www.cnblogs.com/zhq-blog/p/9619468.html
Copyright © 2011-2022 走看看