练习

来源:互联网 发布:js中不等于空 编辑:程序博客网 时间:2024/04/29 16:47
//队列:队头删除,队尾插入


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


struct queue_data
{
int queue;
struct queue_data* next;
};


typedef struct queue_data Queue;
typedef struct queue_data* Link;


enum return_result{EMPTY_OK,EMPTY_NO,PUSH_OK,PUSH_NO,POP_OK,POP_NO};
//建立头结点


void create_queue(Link *head)
{
(*head) = (Link)malloc(sizeof(Queue));
if(*head == NULL)
{
printf("malloc error!\n");
exit(-1);
}
(*head)->next=(*head);
}


int is_queue_empty(Link front)
{
if (front->next == NULL)
{
return EMPTY_OK;
}else
{
return EMPTY_NO;
}
}


void init_queue(Link *front,Link *rear,Link *head)//初始化
{
*front = *head;
*rear = *head;
}
/*入队*/
int push_queue(Link new_node,Link *rear,int i)
{
create_queue(&new_node);
new_node->queue = i+1;
new_node->next = (*rear)->next;
(*rear)->next = new_node;
return PUSH_OK;
}
/*出队*/
int pop_queue( Link *front )
{
int temp;
if ( is_queue_empty(*front) == EMPTY_OK)
{
printf("the queue is empty!\n");
return POP_NO;
}else
{
temp = (*front)->next->queue;
free((*front)->next);
((*front)->next)=(*front)->next->next;
return temp;
}

}
int main()
{
    Link new_node = NULL;//定义结点
Link front = NULL;
Link rear = NULL;;//定义队头和队尾指针
int i;
int temp;


create_queue(&new_node);//创建结点


init_queue(&front,&rear,&new_node);//初始化


for (i = 0; i < 10; i++)
{
if(push_queue(new_node,&rear,i+1) == PUSH_OK)
{
printf("push ok!\n");
}
}
for ( i = 0 ; i < 10 ; i++ )
{
temp = pop_queue(&front);
    if (temp != POP_NO )
{
printf("%d\n",temp);
}
}


    return 0;
}
0 0