经常看到一些多函数代码明明函数定义在主函数前面仍会先声明一遍函数
按照语法正确性来说 我们知道对于函数的声明与定义一般有两种情况:
1、函数在主函数前定义,此时可以直接声明并定义,即无需先声明函数头;
2、函数在主函数之后定义,在主函数前必须先声明函数;
故之前看到函数定义在前还声明函数的会觉得有点多此一举,今天自己在敲代码的时候才突然发现这样做的好处
#include <stdio.h>
#include <malloc.h>
typedef struct queue {
int num;
int data;
struct queue *next;
}queue;
queue* initqueue(int size);
queue* gettail(queue *head, int *max);
int calculatetimes(queue *head, int m);
void freequeue(queue *head);
queue* initqueue(int size)
{
int i;
queue *head = (queue*)malloc(sizeof(queue));
queue *tail = head;
head->next = NULL;
for (i = 1; i <= size; i++)
{
queue* node = (queue*)malloc(sizeof(queue));
node->num = i;
scanf("%d", &node->data);
tail->next = node;
node->next = NULL;
tail = node;
}
return head;
}
int calculatetimes(queue* head, int m)
{
int max, times = 0;
queue *tail, *pre = head;
head = head->next;
tail = gettail(pre, &max);
while (head)
{
if (head->data != max)
{
pre->next = head->next;
tail->next = head;
head->next = NULL;
tail = head;
head = pre->next;
}
else
{
++times;
if (head->num == m)
break;
else
{
pre->next = head->next;
free(head);
head = pre->next;
tail = gettail(pre, &max);
}
}
}
return times;
}
queue* gettail(queue *head, int *max)
{
*max = 0;
queue* tail = head;
for (head = head->next; head; head = head->next)
{
tail = head;
*max = *max > head->data ? *max : head->data;
}
return tail;
}
void freequeue(queue *head)
{
queue *node = head;
for (head = head->next; head; head = head->next)
{
free(node);
node = head;
}
}
int main(void)
{
int n, m;
queue *head;
scanf("%d%d", &n, &m);
head = initqueue(n);
printf("%d", calculatetimes(head, m));
freequeue(head);
return 0;
}
多函数封装的时候常常会遇到函数嵌套的情况 经常会遇到函数先定义了然后run之后就报错有一些函数uninitialized
所以无论函数定义是否在main之前都先声明一遍函数名应该是一个不错的习惯
可以避免因函数嵌套引起的报错 也会形成更清晰的思路 在声明的时候就思考函数顺序如何摆放的问题
看似多此一举但是还是一个挺好的习惯的
以后写的时候可以多注意一下