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将队列指针传递进去。

  • 相关阅读:
    linux 换源
    Jedis使用
    mysql 安装
    ORACLE 11g安装
    网易有道云笔记去除左下角广告
    No module named 'urllib2'
    python+Eclipse+pydev环境搭建
    python-正则表达式基础
    [转]SpringMVC Controller介绍及常用注解
    【Android自学日记】搭建Android开发环境
  • 原文地址:https://www.cnblogs.com/zhq-blog/p/9619468.html
Copyright © 2011-2022 走看看