C语言实现单链表(不带头结点)节点的插入

本文介绍了如何在C语言中实现单链表(不带头结点)的节点插入操作,这是链表操作的基础。作者提供了删除节点的先前教程,并分享了插入节点的示例代码,代码已上传至GitHub仓库https://github.com/chenyufeng1991/InsertList。
摘要由CSDN通过智能技术生成

       对单链表进行增删改查是最基本的操作。我在上一篇博客《C语言实现链表节点的删除》实现了删除单链表中的某个节点。这里我们要来实现在某个位置插入节点。示例代码上传至https://github.com/chenyufeng1991/InsertList  。

核心代码如下:

Node *InsertToPosition(Node *pNode,int pos,int x){

    if (pos < 0 || pos > sizeList(pNode) ) {
        printf("%s函数执行,pos=%d非法,插入数据失败\n",__FUNCTION__,pos);
        return pNode;
    }

    Node *pMove;
    Node *pInsert;
    pInsert = (Node *)malloc(sizeof(Node));
    memset(pInsert, 0, sizeof(Node));
    pInsert->next = NULL;
    pInsert->element =
以下是用C语言实现不带头结点单链表的基本操作的代码: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 struct Node { int data; // 数据域 struct Node* next; // 指针域 }; // 在链表尾部插入节点 void insertAtEnd(struct Node** head_ref, int new_data) { struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // 创建新节点 struct Node* last = *head_ref; // 定义指向最后一个节点的指针 new_node->data = new_data; // 填充新节点数据 new_node->next = NULL; // 新节点的 next 指针赋值为空 // 如果链表为空,将新节点设为头节点 if (*head_ref == NULL) { *head_ref = new_node; return; } // 遍历链表,找到最后一个节点 while (last->next != NULL) { last = last->next; } // 将新节点接在链表尾部 last->next = new_node; } // 在链表中删除指定值的节点 void deleteNode(struct Node** head_ref, int key) { struct Node* temp = *head_ref; // 定义指向当前节点的指针 struct Node* prev = NULL; // 定义指向当前节点前一个节点的指针 // 如果头节点的数据为要删除的数据 if (temp != NULL && temp->data == key) { *head_ref = temp->next; // 修改头节点 free(temp); // 释放原头节点内存 return; } // 遍历链表,找到要删除的节点 while (temp != NULL && temp->data != key) { prev = temp; temp = temp->next; } // 如果找到了要删除的节点 if (temp != NULL) { prev->next = temp->next; // 修改前一个节点的 next 指针 free(temp); // 释放要删除的节点内存 } } // 打印链表 void printList(struct Node* node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } printf("\n"); } int main() { struct Node* head = NULL; // 定义头节点 // 在链表尾部插入节点 insertAtEnd(&head, 1); insertAtEnd(&head, 2); insertAtEnd(&head, 3); printf("Original list: "); printList(head); // 删除节点 deleteNode(&head, 2); printf("Updated list: "); printList(head); return 0; } ``` 运行结果: ``` Original list: 1 2 3 Updated list: 1 3 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值