本章重点:
- 了解部分规范即可
函数的由来与好处
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <windows.h> #define N 10 typedef struct _Node { int data; struct _Node* next; }node_t; static node_t* AllocNode(int x) { node_t* n = (node_t*)malloc(sizeof(node_t)); if (NULL == n) { exit(EXIT_FAILURE); } n->data = x; n->next = NULL; return n; } void InsertList(node_t* head, int x) { node_t* end = head; while (end->next) { end = end->next; } node_t* n = AllocNode(x); end->next = n; } void ShowList(node_t* head) { node_t* p = head->next; while (p) { printf("%d ", p->data); p = p->next; } printf("\n"); } void DeleteList(node_t* head) { node_t* n = head->next; if (n != NULL) { head->next = n->next; free(n); } } int main() { node_t* head = AllocNode(0); //方便操作,使用带头结点的单链表 printf("插入演示...\n"); Sleep(10000); for (int i = 1; i <= N; i++) { InsertList(head, i); //插入一个节点,尾插方案 ShowList(head); //显示整张链表 Sleep(1000); } printf("删除演示...\n"); for (int i = 1; i <= N; i++) { DeleteList(head); //删除一个节点,头删方案 ShowList(head); //显示整张链表 Sleep(1000); } free(head); //释放头结点 head = NULL; return 0; }
上面我们写的单链表插入和删除的例子,每个操作都有新节点的产生,我们可以把节点申请单独写成一个函数,这样当任 何一个场景想申请节点的时候,可以直接通过调用函数的方式进行,而不用在进行冗余的代码编写。
函数的基本语法格式
编码风格
One
Two
Three
Four
Five
Six
Seven
Eight
Nine
Ten
Eleven
Twelve
Thirteen
Fourteen
Fifteen
Sixteen
Seventeen
Eighteen
【突破常规:让函数规范成为注目的亮点】(下):https://developer.aliyun.com/article/1424733