队列的链表实现

#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
//此处构建两个结构体,如果将front和rear两个指针放入node结构体时,每次添加元素时都会创建新的front和rear指针
typedef struct node
{
    datatype data;
    struct node * next;
}node_t,*node_p;

typedef struct node_pointer
{
    node_p front;
    node_p rear;
}node_pointer_t,*node_pointer_p;
node_pointer_p squ_create();
int squ_push(node_pointer_p P,datatype value);
int squ_pop(node_pointer_p P);
int squ_empty(node_pointer_p P);
int main(int argc, const char *argv[])
{
    node_pointer_p P = squ_create();
    if(NULL == P)
    {
        printf("函数调用失败\n");
        return -1;
    }
    squ_push(P,1);
    squ_push(P,2);
    squ_push(P,3);
    squ_push(P,4);
    squ_pop(P);
    squ_pop(P);
    squ_pop(P);
    squ_pop(P);
    squ_pop(P);
    return 0;
}

//为node_t和node_pointer_t创建内存空间
node_pointer_p squ_create()
{
    node_p S = (node_p)malloc(sizeof(node_t));
    if(NULL == S)
    {
        printf("栈空间内存开辟失败\n");
        return NULL;
    }
    S->next = NULL;

    node_pointer_p P = (node_pointer_p)malloc(sizeof(node_pointer_t));
    if(NULL == P)
    {
        free(S);
        S = NULL;
        printf("指向栈空间的指针内存开辟失败\n");
        return NULL;
    }
    P->front = S;
    P->rear = S;
    return P;
}
//入队
int squ_push(node_pointer_p P,datatype value)
{
    node_p S = (node_p)malloc(sizeof(node_t));
    if(S==NULL)
    {
        printf("开辟空间失败\n");
        return -1;
    }
    S->data = value;
    S->next = NULL;
    P->rear->next = S;
    P->rear = S;
    return 0;
}

//出队
int squ_pop(node_pointer_p P)
{
    if(squ_empty(P))
    {
        printf("队列已空\n");
        return -1;
    }
    int value;
    value = P->front->next->data;
    node_p S = P->front;
    printf("pop : %d\n",value);
    P->front = P->front->next;
    free(S);
    return 0;
}

//判断队列是否为空
int squ_empty(node_pointer_p P)
{
    return P->front == P->rear;
}

 

posted on 2019-04-18 14:53  骉赑  阅读(92)  评论(0编辑  收藏  举报

导航