在C语言中,当你想要在函数内部修改一个指针的值时,
你需要传递该指针的地址,即指向该指针的指针。
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点的结构体
typedef struct Node {
int data; // 数据域,存储节点的值
struct Node* next; // 指针域,指向下一个节点
} Node;
// 在顺序递增链表中插入新节点
/* Node** headRef 这样,使用双层指针的原因是:
在C语言中,当你想要在函数内部修改一个指针的值时,
你需要传递该指针的地址,即指向该指针的指针。
这是因为C语言中的函数参数是按值传递的,
这意味着函数接收的是参数值的一个副本,而不是参数本身。
如果你只传递指针本身,那么在函数内部对指针的任何修改都只会影响这个副本,
而不会影响原始的指针。
举个简单的例子:
========================================
void get_values(int *a, int *b) {
*a = 10;
*b = 20;
}
int main() {
int x, y;
get_values(&x, &y);//函数内部的操作已经通过指针传递到了函数外部,通过指针修改了传入的变量。
printf("x: %d, y: %d\n", x, y); // 输出:x: 10, y: 20
return 0;
}
========================================
*/
void insertInOrder(Node** headRef, int value) {
// 分配新节点的内存
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("内存分配失败\n");
return;
}
newNode->data = value; // 设置新节点的数据
newNode->next = NULL; // 新节点的下一个节点设置为NULL
// 如果链表为空,或者新节点的值小于头节点的值,新节点成为新的头节点
if (*headRef == NULL || (*headRef)->data >= newNode->data) {
newNode->next = *headRef;
*headRef = newNode;
return;
}
// 寻找插入位置
Node* current = *headRef;
while (current->next != NULL && current->next->data < newNode->data) {
current = current->next;
}
// 在 current 和 current->next 之间插入新节点
newNode->next = current->next;
current->next = newNode;
}
int main() {
Node* head = NULL; // 初始化链表为空
// 插入节点
insertInOrder(&head, 20);
insertInOrder(&head, 10);
insertInOrder(&head, 30);
insertInOrder(&head, 25);
// 打印链表
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
// 释放链表内存
Node* current = head;
while (current != NULL) {
Node* next = current->next;
free(current);
current = next;
}
return 0;
}