欢迎光临散文网 会员登陆 & 注册

C/C++编程笔记:链接列表(链表)丨删除节点的操作源码

2020-12-11 21:00 作者:C语言编程__Plus  | 我要投稿

我们已经在以前关于单链接列表的文章中讨论了“链接列表介绍”和“链接列表插入”。

让我们制定问题陈述以了解删除过程。给定一个“键”,删除该键在链表中的第一个匹配项。 

要从链接列表中删除节点,我们需要执行以下步骤。 

1)找到要删除的节点的上一个节点。 

2)更改上一个节点的下一个节点。 

3)待删除节点的可用内存。


由于链表的每个节点都是使用C语言中的malloc()动态分配的,因此我们需要调用free()来释放为要删除的节点分配的内存。

C ++

#include <bits/stdc++.h>

usingnamespacestd;

classNode{

public:

    intdata;

    Node* next;

};

voidpush(Node** head_ref, intnew_data)

{

    Node* new_node = newNode();

    new_node->data = new_data;

    new_node->next = (*head_ref);

    (*head_ref) = new_node;

}

voiddeleteNode(Node** head_ref, intkey)

{

    Node* temp = *head_ref;

    Node* prev = NULL;

    if(temp != NULL && temp->data == key)

    {

        *head_ref = temp->next; 

        delete temp;           

        return;

    }

    while(temp != NULL && temp->data != key)

    {

        prev = temp;

        temp = temp->next;

    }

    if(temp == NULL)

        return;

    prev->next = temp->next;

    delete temp;

}

voidprintList(Node* node)

{

    while(node != NULL) 

    {

        cout << node->data << " ";

        node = node->next;

    }

}

intmain()

{

    Node* head = NULL;

    push(&head, 7);

    push(&head, 1);

    push(&head, 3);

    push(&head, 2);

    puts("Created Linked List: ");

    printList(head);

    deleteNode(&head, 1);

    puts("\nLinked List after Deletion of 1: ");

    printList(head);

    return 0;

}

C语言

#include <stdio.h>

#include <stdlib.h>

structNode

{

    intdata;

    structNode *next;

};

voidpush(structNode** head_ref, intnew_data)

{

    structNode* new_node = (structNode*) malloc(sizeof(structNode));

    new_node->data  = new_data;

    new_node->next = (*head_ref);

    (*head_ref)    = new_node;

}

voiddeleteNode(structNode **head_ref, intkey)

{

    structNode* temp = *head_ref, *prev;

    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) return;

    prev->next = temp->next;

    free(temp);  

}

voidprintList(structNode *node)

{

    while(node != NULL)

    {

        printf(" %d ", node->data);

        node = node->next;

    }

}

int main()

{

    structNode* head = NULL;

    push(&head, 7);

    push(&head, 1);

    push(&head, 3);

    push(&head, 2);

    puts("Created Linked List: ");

    printList(head);

    deleteNode(&head, 1);

    puts("\nLinked List after Deletion of 1: ");

    printList(head);

    return0;

}

输出: 

创建的链接列表:  2 3 1 7

删除后的链接列表:  2 3 7

希望对你有帮助~

另外如果你想更好的提升你的编程能力,学好C语言C++编程!弯道超车,快人一步!笔者这里或许可以帮到你~

UP在主页上传了一些学习C/C++编程的视频教程,有兴趣或者正在学习的小伙伴一定要去看一看哦!会对你有帮助的~

分享(源码、项目实战视频、项目笔记,基础入门教程)

欢迎转行和学习编程的伙伴,利用更多的资料学习成长比自己琢磨更快哦!

编程学习书籍分享:


编程学习视频分享:



C/C++编程笔记:链接列表(链表)丨删除节点的操作源码的评论 (共 条)

分享到微博请遵守国家法律