insertInOrder(Node** headRef, int value)

在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;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九层指针

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值