1.链栈、循环队列代码
链栈:
#include"link_stack.h"
//创建空的链栈,形参需要接受主函数内的实参
void create_link_stack(node_p *S)
{
*S = NULL;
}
//申请结点
node_p create_node(char data)
{
node_p new = (node_p)malloc(sizeof(node));
if(new==NULL)
{
printf("空间申请失败\n");
return NULL;
}
new->data = data;
return new;
}
//入栈、压栈(头插)
void push_stack(node_p *S,char data)
{
if(S==NULL)
{
printf("入参为空,请检查\n");
return;
}
node_p new = create_node(data);
new->next = *S;
*S = new;
}
//出栈、弹栈(头删)
void pop_stack(node_p *S)
{
if(S==NULL)
{
printf("入参为空,请检查\n");
return;
}
if(empty_stack(*S))
{
printf("栈空,无需出栈\n");
return;
}
node_p del = *S;
*S = del->next;
printf("出栈元素为:%c\n",del->data);
free(del);
}
//判空
int empty_stack(node_p S)
{
return S==NULL?1:0;
}
//输出
void show_stack(node_p S)
{
if(S==NULL)
{
printf("入参为空,请检查\n");
return;
}
if(empty_stack(S))
{
printf("栈空\n");
return;
}
node_p p = S;
while(p!=NULL)
{
printf("%c\n",p->data);
p = p->next;
}
}
循环队列:
代码:
#include"que.h"
//创建循环队列
queue *create_q()
{
queue_p Q = (queue_p)malloc(sizeof(queue));
if(Q==NULL)
{
printf("空间申请失败\n");
return NULL;
}
Q->front = 0;
Q->rear = 0;
return Q;
}
//判空
int empty_queue(queue *Q)
{
return Q->rear==Q->front?1:0;
}
//判满
int full_queue(queue *Q)
{
return (Q->rear+1)%MAX==Q->front?1:0;
}
//入队
void push_queue(queue *Q,datatype data)
{
if(Q==NULL)
{
printf("入参为空,请检查\n");
return;
}
if(full_queue(Q))
{
printf("队列已满,无法入队\n");
return;
}
Q->data[Q->rear] = data;
Q->rear = (Q->rear+1)%MAX;
}
//出队
void pop_queue(queue *Q)
{
if(Q==NULL)
{
printf("入参为空,请检查\n");
return;
}
if(empty_queue(Q))
{
printf("队列为空\n");
return;
}
printf("出队的元素为:%d\n",Q->data[Q->front]);
Q->front = (Q->front+1)%MAX;
}
//销毁队列
void free_queue(queue *Q)
{
if(Q==NULL)
{
printf("入参为空,请检查\n");
return;
}
free(Q);
Q = NULL;
}
//输出队列
void show(queue *Q)
{
if(Q==NULL)
{
printf("入参为空,请检查\n");
return;
}
if(empty_queue(Q))
{
printf("队列为空\n");
return;
}
for(int i=Q->front;i!=Q->rear;i=(i+1)%MAX)
{
printf("%d ",Q->data[i]);
}
}
结果:
2.猴子吃桃
代码:
#include<myhead.h>
int fun(int n)
{
int a;
if(n==10)
return 1;
else
return 2*fun(n+1)+2;
}
int main(int argc, const char *argv[])
{
int b;
printf("请输入想要知道第几天桃子的数量:\n");
scanf("%d",&b);
int n=fun(b);
printf("桃子数量:%d\n",n);
return 0;
}
结果:
3.思维导图