C++中删除给定位置的链表节点
在本教程中,我们将学习如何在给定位置的单链表中删除一个节点。
让我们看看解决问题的步骤。
编写包含数据和下一个指针的结构体。
编写一个函数将节点插入到单链表中。
使用虚拟数据初始化单链表。
初始化要删除节点的位置。
遍历链表并找到要删除的给定位置的节点。
编写一个删除节点的函数。删除节点时,请考虑以下三种情况。
如果节点是头节点,则将头节点移动到下一个节点。
如果节点是中间节点,则将下一个节点链接到前一个节点。
如果节点是尾节点,则删除前一个节点的链接。
示例
让我们看看代码
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *next;
};
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->next = (*head_ref);
(*head_ref) = new_node;
}
void deleteNode(struct Node **head_ref, int position) {
if (*head_ref == NULL) {
return;
}
struct Node* temp = *head_ref;
if (position == 1) {
*head_ref = temp->next;
free(temp);
return;
}
for (int i = 2; temp != NULL && i < position - 1; i++) {
temp = temp->next;
}
if (temp == NULL || temp->next == NULL) {
return;
}
struct Node *next = temp->next->next;
free(temp->next);
temp->next = next;
}
void printLinkedList(struct Node *node) {
while (node != NULL) {
cout << node->data << "->";
node = node->next;
}
}
int main() {
struct Node* head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
insertNode(&head, 4);
insertNode(&head, 5);
cout << "Linked list before deletion:" << endl;
printLinkedList(head);
deleteNode(&head, 1);
cout << "\nLinked list after deletion:" << endl;
printLinkedList(head);
return 0;
}输出
如果执行上述程序,则会得到以下结果。
Linked list before deletion: 5->4->3->2->1-> Linked list after deletion: 4->3->2->1->
结论
如果您在本教程中有任何疑问,请在评论区提出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP