在 C++ 中删除列表中所有大于 x 的节点


在本教程中,我们将学习如何从单链表中删除所有素数节点。

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

  • 编写带有数据和下一个指针的结构体。

  • 编写一个函数将节点插入到单链表中。

  • 使用虚拟数据初始化单链表。

  • 遍历单链表。查找当前节点数据是否大于 x。

  • 如果当前数据大于 x,则删除该节点。

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

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

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

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

示例

让我们看看代码。

 实时演示

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   Node* next;
};
Node* getNewNode(int data) {
   Node* newNode = new Node;
   newNode->data = data;
   newNode->next = NULL;
   return newNode;
}
void deleteGreaterNodes(Node** head_ref, int x) {
   Node *temp = *head_ref, *prev;
   if (temp != NULL && temp->data > x) {
      *head_ref = temp->next;
      free(temp);
      temp = *head_ref;
   }
   while (temp != NULL) {
      while (temp != NULL && temp->data <= x) {
         prev = temp;
         temp = temp->next;
      }
      if (temp == NULL) {
         return;
      }
      prev->next = temp->next;
      delete temp;
      temp = prev->next;
   }
}
void printLinkedList(Node* head) {
   while (head) {
      cout << head->data << " -> ";
      head = head->next;
   }
}
int main() {
   Node* head = getNewNode(1);
   head->next = getNewNode(2);
   head->next->next = getNewNode(3);
   head->next->next->next = getNewNode(4);
   head->next->next->next->next = getNewNode(5);
   head->next->next->next->next->next = getNewNode(6);
   int x = 3;
   cout << "Linked List before deletion:" << endl;
   printLinkedList(head);
   deleteGreaterNodes(&head, x);
   cout << "\nLinked List after deletion:" << endl;
   printLinkedList(head);
   return 0;
}

输出

如果执行上述程序,则会得到以下结果。

Linked List before deletion:
1 -> 2 -> 3 -> 4 -> 5 -> 6 ->
Linked List after deletion:
1 -> 2 -> 3 ->

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+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告