下面是用C语言实现在一个链表中间插入一个元素的示例代码:

#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构体
struct Node {
    int data;           // 节点数据
    struct Node* next;  // 指向下一个节点的指针
};

// 在链表头部插入节点
struct Node* insertAtBeginning(struct Node* head, int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));   // 创建新节点
    newNode->data = data;                                               // 设置新节点的数据
    newNode->next = head;                                               // 将新节点的next指向原链表的头节点
    head = newNode;                                                      // 将新节点设置为链表的新头节点
    return head;                                                         // 返回新的头节点
}

// 在链表中间插入节点
void insertInMiddle(struct Node* head, int data, int position) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));   // 创建新节点
    newNode->data = data;                                               // 设置新节点的数据
    struct Node* current = head;                                        // 从头节点开始遍历链表
    int i;
    for (i = 1; i < position && current != NULL; i++) {                 // 找到插入位置的前一个节点
        current = current->next;
    }
    if (current == NULL) {                                              // 如果插入位置超出链表长度,则不插入
        printf("Position out of range.\n");
        return;
    }
    newNode->next = current->next;                                      // 将新节点的next指向插入位置的后一个节点
    current->next = newNode;                                            // 将插入位置的前一个节点的next指向新节点
}

// 打印链表
void printList(struct Node* head) {
    struct Node* current = head;                                        // 从头节点开始遍历链表
    printf("List: ");
    while (current != NULL) {                                           // 遍历整个链表
        printf("%d ", current->data);                                   // 输出节点的数据
        current = current->next;                                        // 移动到下一个节点
    }
    printf("\n");
}

// 主函数
int main() {
    struct Node* head = NULL;                                           // 初始化链表为空
    head = insertAtBeginning(head, 1);                                   // 在链表头部插入1
    head = insertAtBeginning(head, 2);                                   // 在链表头部插入2
    head = insertAtBeginning(head, 3);                                   // 在链表头部插入3
    printList(head);                                                     // 输出链表
    insertInMiddle(head, 4, 2);                                          // 在链表中间插入4
    printList(head);                                                     // 输出链表
    insertInMiddle(head, 5, 5);                                          // 尝试在插入位置超出链表长度的位置插入5
    return 0;
}

运行结果:

List: 3 2 1 
List: 3 2 4 1 
Position out of range.
``
用C语言实现在一个链表中间插入一个元素

原文地址: http://www.cveoy.top/t/topic/eCFM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录