C語言隊列的各項操做

/*************************************************************************
    > File Name: new_queue.c
    > Author:heathcliff 
    > Mail: ------------------- 
    > Created Time: 2016年04月02日 星期六 13時22分48秒
 ************************************************************************/
#include<stdio.h>
#include<stdlib.h>

typedef int ElemType;
typedef struct node
{
    ElemType data;
    struct node *next;
}que_node;

struct que
{
    que_node *front,*rear; //建立隊頭、隊尾指針
};

int length = 0;//計算隊列的長度

void init_queue(struct que *q);
void enter_queue(struct que *q,ElemType x);
ElemType delete_queue(struct que *q);
void print(struct que q);

int main(void)
{
    struct que *q;
    int x,interrupt;

    q = (struct que *) malloc (sizeof(struct que));//此步驟必須有,不然會引發程序崩潰
    init_queue(q);

    printf("\n請輸入你想要入對的值,以0結束:");
    scanf("%d",&x);

    while( x != 0){
        enter_queue(q,x);
        scanf("%d",&x);
    }
    print(*q);
    printf("length = %d\n",length);

    printf("請問是否要出對操做:yes (1),no(0)\n");
    scanf("%d",&interrupt);

    while(length){
        if(interrupt == 1){
            x = delete_queue(q);
            printf("\n出對元素爲:%d",x);
            printf("\nlength = %d \n",length);

            printf("請問是否繼續出對:yes (1),no(0)\n");
            scanf("%d",&interrupt);
            }
        else
            exit(0);
        }

    return 0;
}

void init_queue(struct que *q)
{
    que_node *head; //建立頭指針

    head = (que_node *) malloc (sizeof(que_node));

    head->next = NULL;
    q->rear = head;
    q->front = head;
}

/*入對操做*/
void enter_queue(struct que *q ,ElemType x)
{
    que_node *p;

    p = (que_node *) malloc (sizeof(que_node));//分配空間

    p->data = x;//賦值
    /*入對操做在隊尾,即rear上進行*/
    p->next = NULL;
    q->rear->next = p;
    q->rear = p;//指針向後移動一位

    length ++ ;
}

/*出對操做*/
ElemType delete_queue(struct que *q)
{
    que_node *p;
    int keep;

    p = (que_node *) malloc (sizeof(que_node));//分配空間
    /*出對操做在隊頭進行,即front*/
    if(q->front == q->rear){// 隊列爲空
        printf("隊列爲空");
        keep = 0;
    }
    else{
        p = q->front->next;
        q->front->next = p->next;//隊頭後移一位

        if(p->next == NULL)
            q->front = q->rear;
        keep = p->data ;//保存出對元素的值
    }

    length -- ;
    return keep;
}

/*打印隊列*/
void print(struct que q)
{
    que_node *p;
    p = (que_node *) malloc (sizeof(que_node));
    p = q.front->next;

    while(p != NULL){
        printf("data = %d\n",p->data);  

        p = p->next;
    }
}
相關文章
相關標籤/搜索