C++中删除双向链表中指定位置的节点


在本教程中,我们将学习如何删除双向链表中给定位置的节点。

让我们看看解决这个问题的步骤。

  • 编写包含数据、前指针和后指针的结构体。

  • 编写一个函数将节点插入双向链表。

  • 用虚拟数据初始化双向链表。

  • 初始化要删除节点的位置。

  • 遍历链表并找到要删除的给定位置的节点。

  • 编写一个删除节点的函数。删除节点时,请考虑以下三种情况。

    • 如果节点是头节点,则将头节点移动到下一个节点。

    • 如果节点是中间节点,则将下一个节点链接到上一个节点。

    • 如果节点是尾节点,则移除上一个节点的链接。

示例

让我们看看代码。

 在线演示

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node *prev, *next;
};
void deleteNode(struct Node** head_ref, struct Node* del) {
   if (*head_ref == NULL || del == NULL) {
      return;
   }
   // head node
   if (*head_ref == del) {
      *head_ref = del->next;
   }
   // middle node
   if (del->next != NULL) {
      del->next->prev = del->prev;
   }
   // end node
   if (del->prev != NULL) {
      del->prev->next = del->next;
   }
   free(del);
}
void deleteNodeAtGivenPosition(struct Node** head_ref, int n) {
   if (*head_ref == NULL || n <= 0) {
      return;
   }
   struct Node* current = *head_ref;
   int i;
   for (int i = 1; current != NULL && i < n; i++) {
      current = current->next;
   }
   if (current == NULL) {
      return;
   }
   deleteNode(head_ref, current);
}
void insertNode(struct Node** head_ref, int new_data) {
   struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
   new_node->data = new_data;
   new_node->prev = NULL;
   new_node->next = (*head_ref);
   if ((*head_ref) != NULL) {
      (*head_ref)->prev = new_node;
   }
   (*head_ref) = new_node;
}
void printLinkedList(struct Node* head) {
   while (head != NULL) {
      cout << head->data << "->";
      head = head->next;
   }
}
int main() {
   struct Node* head = NULL;
   insertNode(&head, 5);
   insertNode(&head, 2);
   insertNode(&head, 4);
   insertNode(&head, 8);
   insertNode(&head, 10);
   cout << "Doubly linked list before deletion" << endl;
   printLinkedList(head);
   int n = 2;
   deleteNodeAtGivenPosition(&head, n);
   cout << "\nDoubly linked list after deletion" << endl;
   printLinkedList(head);
   return 0;
}

输出

如果执行上述程序,您将得到以下结果。

Doubly linked list before deletion
10->8->4->2->5->
Doubly linked list after deletion
10->4->2->5->

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

结论

如果您在本教程中有任何疑问,请在评论部分提出。

更新于:2020年12月30日

2K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告