海康威视笔试题—用链表实现一个队列

海康威视笔试题—用链表实现一个队列

记住队列的特点,先进先出就好了

然后还有就是成程序设计要注意程序的一个健壮性,一些不好的编程习惯可能会让你的代码等级降低许多

遇到问题:对函数的形参进行操作,导致没有正确删除队列

代码如下:

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

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

//定义一个队列(保存的是队列的头指针和尾指针)
typedef struct queue_link
{
    node * front;
    node * rear;
}queue;

//队列初始化函数
queue * InitQueue()
{
    queue * q = (queue *)malloc(sizeof(queue));
    if(q == NULL)
    {
        return NULL;
    }
    q->front = q->rear = NULL;
    return q;
}

//从尾部入队
int InsertQueue(queue * q, int data)
{
    node * n = (node *)malloc(sizeof(node));
    if(n == NULL)
    {
        return -1;
    }
    n->data = data;
    n->next = NULL;
    //当前队列为空
    if(q->rear == NULL)
    {
        q->rear = n;
        q->front = n;
    }
    else
    {
        //先把新节点插入
        q->rear->next = n;
        //再把新节点设置为尾节点
        q->rear = n;
    }

}
//出队操作,从头部出去

int Delete_Queue(queue *q)
{
    if(q == NULL)
    {
        return -1;
    }
    node * n = q->front;
    //当队列为空时
    if(q->front == NULL)
    {
        return -1;
    }
    //当队列只有一个元素时
    if(q->front == q->rear)
    {
        if(q != NULL)
        {
            q->front = NULL;
            q->rear = NULL;
            free(n);
            n = NULL;
        }
    }
    else
    {
        q->front = q->front->next;
        //这里只有设置一个node * n = q->front;才能操作到队列的数字
        free(n);
    }

}

//打印队列
int Display(queue *q)
{
    if(q->front == NULL)
    {
        return -1;
    }
    node *n = (node*)malloc(sizeof(node));
    if(n == NULL)
    {
        return;
    }
    n = q->front;
    while(n != NULL)
    {
       printf("%d", n->data);
       n = n->next;
    }
    printf("\n");
    free(n);
}

//判断队列是否为空
int IsEmpty(queue * q)
{
    if(q == NULL)
    {
        return -1;
    }
    return q->front == NULL;
}
void func(int *a)
{
    *a = 4;
}
int main(void)
{
    int i, j;
    i = 5; j = 5;
    queue * q;
    q = InitQueue();
    printf("开始入队:\n");
    while(i--)
    {
        printf("元素%d入队,队列为:", i);
        InsertQueue(q, i);
        Display(q);
    }
    while(j--)
    {
        printf("第%d个元素出队,队列为:",5 - j);
        Delete_Queue(q);
        Display(q);
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值