海康威视笔试题—用链表实现一个队列
记住队列的特点,先进先出就好了
然后还有就是成程序设计要注意程序的一个健壮性,一些不好的编程习惯可能会让你的代码等级降低许多
遇到问题:对函数的形参进行操作,导致没有正确删除队列
代码如下:
#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;
}