在C ++中从列表中删除所有大于x的节点
在本教程中,我们将学习如何从单链列表中删除所有主要节点。
让我们看看解决问题的步骤。
用数据和下一个指针写struct。
编写一个函数以将节点插入到单链列表中。
用伪数据初始化单链表。
遍历单链表。查找当前节点数据是否大于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 << "删除前的链表:" << endl;
printLinkedList(head);
deleteGreaterNodes(&head, x);
cout << "\nLinked List after deletion:" << endl;
printLinkedList(head);
return 0;
}输出结果如果执行上述程序,则将得到以下结果。
删除前的链表: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> Linked List after deletion: 1 -> 2 -> 3 ->
结论
如果您对本教程有任何疑问,请在评论部分中提及。