📜  修改链表 (1)

📅  最后修改于: 2023-12-03 14:50:01.129000             🧑  作者: Mango

修改链表

链表是程序中常用的一种数据结构,它由一系列的节点组成,每个节点包含一个指向下一个节点的指针。修改链表是常见的操作之一,本文将介绍如何在链表中进行插入、删除和更新等操作。

插入节点

插入节点是向链表中添加新节点的操作。插入节点有两种方式:在链表头插入节点和在链表尾插入节点。具体实现如下:

在链表头插入节点
// 定义链表节点结构体
struct ListNode {
    int val;
    struct ListNode *next;
};

// 在链表头插入节点
struct ListNode* insertAtHead(struct ListNode* head, int val) {
    struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
    newNode->val = val;
    newNode->next = head;
    return newNode;
}
在链表尾插入节点
// 在链表尾插入节点
struct ListNode* insertAtTail(struct ListNode* head, int val) {
    struct ListNode* pNode = head;
    struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
    newNode->val = val;
    newNode->next = NULL;
    // 遍历到链表尾
    while (pNode->next != NULL) {
        pNode = pNode->next;
    }
    pNode->next = newNode;
    return head;
}
删除节点

删除节点是从链表中删除一个指定节点的操作。删除节点有两种方式:删除指定节点和删除指定位置的节点。具体实现如下:

删除指定节点
// 删除指定节点
struct ListNode* deleteNode(struct ListNode* head, struct ListNode* target) {
    if (head == NULL) {
        return head;
    }
    if (target == head) {
        head = head->next;
        free(target);
        return head;
    }
    struct ListNode* pNode = head;
    while (pNode->next != NULL && pNode->next != target) {
        pNode = pNode->next;
    }
    if (pNode->next == target) {
        pNode->next = target->next;
        free(target);
    }
    return head;
}
删除指定位置的节点
// 删除指定位置的节点
struct ListNode* deleteAtPosition(struct ListNode* head, int position) {
    if (head == NULL) {
        return head;
    }
    if (position == 0) {
        struct ListNode* temp = head;
        head = head->next;
        free(temp);
        return head;
    }
    struct ListNode* pNode = head;
    for (int i = 0; i < position - 1 && pNode->next != NULL; i++) {
        pNode = pNode->next;
    }
    if (pNode->next != NULL) {
        struct ListNode* temp = pNode->next;
        pNode->next = temp->next;
        free(temp);
    }
    return head;
}
更新节点

更新节点是用新值替换链表中一个节点的值的操作。具体实现如下:

更新指定节点的值
// 更新指定节点的值
void updateNodeValue(struct ListNode* head, int oldVal, int newVal) {
    struct ListNode* pNode = head;
    while (pNode != NULL && pNode->val != oldVal) {
        pNode = pNode->next;
    }
    if (pNode != NULL) {
        pNode->val = newVal;
    }
}
总结

本文介绍了如何在链表中进行插入、删除和更新等操作。以上代码片段仅供参考,具体实现需要根据不同的场景进行灵活修改。