现在的位置: 首页 > 综合 > 正文

queue.c

2013年08月20日 ⁄ 综合 ⁄ 共 2303字 ⁄ 字号 评论关闭

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define ERR -1
#define SUC 0

#ifdef LINK_QUEUE
typedef struct Node{
    unsigned int num;
    struct Node *next;
}Node_S;

typedef struct Point{
    Node_S *front;
    Node_S *rear;
}Que_S;
 
Que_S *head;
Node_S *del;

int queue_init()
{
    head = (Que_S* )malloc(sizeof(Que_S));
    if(head == NULL){
        perror("malloc fail");
        return ERR;
    }    
    
    head->front = (Node_S *)malloc(sizeof(Node_S));
    if(head->front == NULL){
        perror("malloc fail:");
        return ERR;
    }
 
    head->rear = head->front;
    head->front->next = NULL;
    del = head->front;
}

void free_queue(int num)
{
    int i = 0;
    Node_S *p = NULL;
    
    for(i = 0; i < num; i++){
        if(head->front == head->rear){
            printf("empty\n");
            return ;
        }

        p = head->front->next;
        head->front->next = p->next;

        if(p == head->rear){
        head->front == head->rear;
        }

        printf("p->num:%d\n",p->num);
        free(p);
    }

    free(del);
}
int add_queue(int i)
{
    Node_S *NewNode = NULL;
    
    NewNode = (Node_S *)malloc(sizeof(Node_S));
    if(NewNode == NULL){
        perror("malloc fail");
        free_queue(i);
        return ERR;
    }   
    
    NewNode->num = i;
    NewNode->next = NULL;
    head->rear->next = NewNode;
    head->rear = NewNode;

    return SUC;
}
#endif

//#ifdef ARRAY_QUEUE
struct msg{
    int data;
};

typedef struct queue{
    struct msg *base;
    int front;
    int rear;
}Node_S;

Node_S *head;

#define MAX_NUM 10
queue_init()
{
    head = (Node_S *)malloc(sizeof(Node_S));
    if(head == NULL){
        perror("head:malloc fail");
        return ;
    }
 
    head->base = (struct msg *)malloc(sizeof(struct msg)*MAX_NUM);
    if(head->base == NULL){
        perror("head->base:malloc fail");
        return ;
    }

    head->front = 0;
    head->rear = 0;
}
//取莫才能形成环模型
//空出一个是为了区分空队列和满队列
//否则仅仅rear = front无法判断
add_queue(num)
{
    if((head->rear+1) % MAX_NUM == head->front){
        printf("queue full\n");
        return ;
    }
    
    head->base[head->rear].data = num;
    head->rear = (head->rear+1) % MAX_NUM;
}

free_queue(num)
{
    int i = 0;

    for(i = 0; i < num; i++){

        if(head->front == head->rear){
            printf("queue empty\n");        
            return ;
        }

        printf("head->front:%d\n",head->base[head->front]);
        head->front = (head->front+1) % MAX_NUM;
    }
    free(head->base);
    free(head);
}

int main()
{
    int i = 0;
    pid_t new;

    queue_init();

    for(i = 0; i < 10; i++){
            add_queue(i);        
    }    

    free_queue(i);
    free(head);
}

抱歉!评论已关闭.