#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
typedef struct
{
struct node *top;
int n;//专门计数
}linkstack;
typedef struct
{
struct node *front;
struct node *rear;
}linkqueue;
linkqueue *create_empty_queue()
{
struct node *head;
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
linkqueue *q;
q = (linkqueue *)malloc(sizeof(linkqueue));
q->front = q->rear = head;
return q;
}
int enter_queue(linkqueue *q,int data)
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = data;
q->rear->next = temp;
temp->next = NULL;
q->rear = temp;
return 0;
}
int is_queue_empty(linkqueue *q)
{
return q->front == q->rear ? 1 : 0;
}
int out_queue(linkqueue *q)
{
if(is_queue_empty(q))
{
printf("error\n");
return -1;
}
struct node *temp;
temp = q->front;
q->front = temp->next;
free(temp);
return q->front->data;
}
linkstack *create_empty_linkstack()
{
linkstack *s;
s = (linkstack *)malloc(sizeof(linkstack));
s->top = NULL;
s->n = 0;
return s;
}
int push_stack(linkstack *s,int data)
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = data;
temp->next = s->top;
s->top = temp;
s->n ++;
return 0;
}
int is_stack_empty(linkstack *s)
{
return s->top == NULL ? 1 : 0;
}
int pop_stack(linkstack *s)
{
if(is_stack_empty(s))
{
printf("the stack is empty\n");
return -1;
}
struct node *temp;
int value;
temp = s->top;
s->top = temp->next;
s->n --;
value = temp->data;
free(temp);
return value;
}
int is_queue_return(linkqueue *q)//如果返回值为0说明队列没还原,如果返回值为1说明队列还原了
{
struct node *p = q->front->next;//队列中头节点后面的第一个节点
int i;
for(i = 1;i <= 27;i ++)
{
if(p->data != i)
return 0;
else
p = p->next;
}
return 1;
}
int ball_time(linkqueue *q,linkstack *min,linkstack *fmin,linkstack *hour)
{
int ball;
int count = 0;
while(1)
{
ball = out_queue(q);//将球出队
if(min->n < 4)//1分钟的栈没有满
{
push_stack(min,ball);
continue;
}
while(!is_stack_empty(min))
{
enter_queue(q,pop_stack(min));
}
if(fmin->n < 11)
{
push_stack(fmin,ball);
continue;
}
while(!is_stack_empty(fmin))
{
enter_queue(q,pop_stack(fmin));
}
if(hour->n < 11)
{
push_stack(hour,ball);
continue;
}
while(!is_stack_empty(hour))
{
enter_queue(q,pop_stack(hour));
}
enter_queue(q,ball);//执行到这里已经正好过了12个小时
count ++;
if(is_queue_return(q) == 1)
break;
}
return count / 2;
}
int main(int argc, const char *argv[])
{
linkqueue *q;
linkstack *min,*fmin,*hour;
q = create_empty_queue();
min = create_empty_linkstack();
fmin = create_empty_linkstack();
hour = create_empty_linkstack();
//将球编号为1-27循环入队
int i;
for(i = 1;i <= 27;i ++)
{
enter_queue(q,i);
}
int days;
days = ball_time(q,min,fmin,hour);
printf("days:%d\n",days);
return 0;
}
作业:球钟问题 球可以代表1分钟,5分钟,1小时。 比如1分钟的球有4个,5分钟的球有8个,1小时的球有10个,对应的时间就是10:44 规定:1分钟的球最多有4个,5分钟的球最多有11个,1小时的
最新推荐文章于 2021-07-31 20:36:42 发布