C语言实现链表的生成、删除、插入

本文介绍了一种使用C语言实现链表的方法,包括创建、显示、插入和删除节点等功能,并提供了完整的代码示例。

C语言实现链表的生成、删除、插入

讲解视频

讲解视频

/*
 * Author:  Mingchong Li
 * Email:   19726006@bjtu.edu.cn
 * Date:    2022/1/8
 */

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


/* Define the node
 * If we don't use `typedef` here,
 * we have to call it `struct nodes` instead of `node`.
*/
typedef struct nodes {
    int num;                     // store data
    struct nodes *next;          // point to the next node
} node;                          // here we can define other names of node

/*
 * Create the a link list for the given array.
 * int x[]: given an integer array
 * int n:   preset the size of array
 */
node *create(int x[], int n) {
    // the head will return at last
    node *head = (node *) malloc(sizeof(node));
    if (n == 0) {
        return NULL;                                    // if here is an empty array
    }
    head->num = x[0];                                   // the first num
    head->next = NULL;                                  // if the array is size of 1, the head will be the tail
    node *p = head;                                     // p is an "allocator", allocate nums from the next of head
    for (int i = 1; i < n; i++) {
        p->next = (node *) malloc(sizeof(node));    // store in heap
        p->next->num = x[i];                             // store the num
        p = p->next;                                     // go to the next
        p->next = NULL;                                  // if it is the end, then next is NULL
    }
    return head;
}

/*
 * display all of the node's num
 */
void display(const node *head) {
    const node *p = head;
    for (; p != NULL; p = p->next) {
        printf("%d ", p->num);      // print until NULL
    }
    printf("\n");
}

/*
 * insert x to the head on n
 * n < 0 or n >= size of link list will return
 */
void insert(node *head, int x, int n) {
    node *p = head;

    if (n == 0) {
        // the head will be copied and insert to the next of head
        insert(head, head->num, 1);
        // change the num of head to x
        head->num = x;
        return;
    } else if (n < 0)
        return;

    // locate to the pre one of n
    for (int i = 0; i < n - 1; i++) {
        p = p->next;
        if (p == NULL)
            return;
    }
    node *preNext = p->next;
    p->next = (node *) malloc(sizeof(node));
    p->next->num = x;
    p->next->next = preNext;
}

/*
 * delete the node position on n
 */
void delete(node *head, int n) {
    node *p = head;

    // we can't delete the head, for the pointer to head couldn't be changed
    // so we just copy the next one to head, and delete the next one
    if (n == 0) {
        p->num = p->next->num;
        delete(head, 1);
    }

    for (int i = 0; i < n - 1; i++) {
        p = p->next;
        if (p == NULL)
            return;
    }

    p->next = p->next->next;            // delete
}

int main() {
    int arr[] = {1, 3, 5, 7, 9};

    node *linkList = create(arr, sizeof(arr) / sizeof(int));
    display(linkList);

    insert(linkList, 0, 0);
    display(linkList);

    delete(linkList, 0);
    display(linkList);

    free(linkList);             // free heap
    return 0;
}
<think>好的,我现在需要帮用户找到用C语言实现链表插入排序的代码示例。用户之前的问题提到了想查找相关的代码或教程,所以我要确保回答结构清晰,符合他们的需求。 首先,我得回忆一下插入排序在链表中的实现方式。根据之前的引用,比如引用[2]提到的是新建一个链表,逐个将原链表的节点插入到新链表的正确位置。这种方法可能比较直观,因为单向链表难以从后往前遍历,所以新建一个链表可以避免频繁的指针操作。 接下来,我需要考虑如何构建这个算法。步骤大致是:遍历原链表的每个节点,然后在新链表中找到合适的插入位置。这里需要注意处理头结点的情况,可能需要一个哑节点(dummy node)来简化插入操作,这样就不必特别处理头部插入的情况了。 然后,我要确保代码的正确性。比如,在插入时,需要维护两个指针,一个指向当前比较的位置,另一个指向前一个节点,以便进行插入。引用[3]提到使用sortprev和sortcur来遍历新链表,找到插入点。如果当前节点的值小于sortcur的值,就插入到sortprev之后,否则继续遍历,直到找到合适的位置或者到达尾部进行尾插。 现在,我需要将这些步骤转化为C语言代码。首先定义链表的结构体,包含数据和next指针。然后实现插入排序函数。在函数内部,创建哑节点作为新链表的起点。遍历原链表,逐个取出节点,并在新链表中找到插入位置。这里需要注意内存管理和指针操作的正确性,避免出现空指针或内存泄漏。 检查代码示例是否包括了必要的部分:链表节点的定义、插入排序函数、以及示例的使用和内存释放。比如,在main函数中创建示例链表,调用排序函数,然后打印结果,最后释放内存。这样用户可以看到完整的流程。 另外,考虑用户可能的疑问,比如如何处理空链表或单个节点的链表,所以在插入排序函数开始时需要检查链表是否为空或只有一个节点,直接返回。同时,在插入过程中,要确保原链表的节点被正确断开,避免形成环。 最后,生成相关问题,帮助用户深入理解。比如插入排序的时间复杂度、优化方法、与其他排序算法的对比,以及处理双向链表的情况。这些问题可以引导用户进一步学习相关的知识点。 总结一下,我需要提供一个结构清晰、注释详细的代码示例,并解释关键步骤,确保用户能够理解实现过程,并通过相关问题扩展他们的知识。</think>### C语言链表插入排序实现 #### 数据结构定义 ```c typedef struct ListNode { int val; struct ListNode* next; } ListNode; ``` #### 插入排序核心算法 ```c ListNode* insertionSortList(ListNode* head) { if (!head || !head->next) return head; // 创建哑节点作为新链表头部 ListNode dummy; dummy.next = NULL; ListNode* curr = head; while (curr) { // 保存下一个节点指针 ListNode* next = curr->next; // 在新链表中寻找插入位置 ListNode* sort_prev = &dummy; ListNode* sort_curr = dummy.next; // 定位插入点 while (sort_curr && sort_curr->val < curr->val) { sort_prev = sort_curr; sort_curr = sort_curr->next; } // 执行插入操作 sort_prev->next = curr; curr->next = sort_curr; curr = next; } return dummy.next; } ``` #### 实现要点解析 1. **哑节点作用**:简化头节点的插入操作,避免特殊判断[^2] 2. **双指针定位**:通过sort_prev和sort_curr遍历已排序部分 3. **时间复杂度**:$O(n^2)$,最优情况(已排序)$O(n)$ 4. **空间复杂度**:$O(1)$,原地排序 #### 完整使用示例 ```c int main() { // 创建示例链表 4->2->1->3 ListNode node4 = {3, NULL}; ListNode node3 = {1, &node4}; ListNode node2 = {2, &node3}; ListNode node1 = {4, &node2}; ListNode* sorted = insertionSortList(&node1); // 打印排序结果 ListNode* p = sorted; while (p) { printf("%d->", p->val); p = p->next; } printf("NULL\n"); return 0; } ```
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Li.MC

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

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

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

打赏作者

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

抵扣说明:

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

余额充值