数据结构单链表之删除给定位置的链表节点第五套

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

给定一个单链表和一个位置,删除给定位置的一个链表节点。

例子:  

输入:位置 = 1,链表 = 8->2->3->1->7
输出:链表 = 8->3->1->7

输入:位置 = 0,链表 = 8->2->3->1->7
输出:链表 = 2->3->1->7
复制代码

如果要删除的节点是根节点,直接删除即可。要删除中间节点,我们必须有一个指向要删除的节点之前的节点的指针。因此,如果位置不为零,我们将循环 position-1 次并获得指向前一个节点的指针。

下面是上述想法的实现。

#include <iostream>
using namespace std;

class Node
{
	public:
	int data;
	Node *next;
};

void push(Node** head_ref, int new_data)
{
	Node* new_node = new Node();
	new_node->data = new_data;
	new_node->next = (*head_ref);
	(*head_ref) = new_node;
}

void deleteNode(Node **head_ref, int position)
{

	if (*head_ref == NULL)
		return;

	Node* temp = *head_ref;

	if (position == 0)
	{
		*head_ref = temp->next;

		free(temp);			
		return;
	}

	for(int i = 0; temp != NULL && i < position - 1; i++)
		temp = temp->next;

	if (temp == NULL || temp->next == NULL)
		return;

	Node *next = temp->next->next;
	free(temp->next);
	temp->next = next;
}

void printList( Node *node)
{
	while (node != NULL)
	{
		cout << node->data << " ";
		node = node->next;
	}
}
int main()
{
	Node* head = NULL;

	push(&head, 7);
	push(&head, 1);
	push(&head, 3);
	push(&head, 2);
	push(&head, 8);

	cout << "创建的链表:";
	printList(head);
	deleteNode(&head, 4);
	cout << "\n位置 4 删除后的链表:";
	printList(head);
	return 0;
}
复制代码

输出:

创建的链表: 
 8 2 3 1 7 
位置 4 删除后的链表: 
 8 2 3 1 
复制代码

🥇 往期优质文章

教你用Java做出一个五子棋小游戏
使用 python 的单人AI 扫雷游戏
数据结构单链表之链表介绍 | 第一套
数据结构单链表之链表与数组 | 第二套
数据结构单链表之链表插入 | 第三套
数据结构单链表之删除节点 | 第四套
手把手教你使用 Python 制作贪吃蛇游戏
手把手教你使用 Java AWT 创建一个简易计算器
使用 HTML、CSS 和 JavaScript 的酷黑主题模拟时钟
使用 HTML、CSS、JS 和 API 制作一个很棒的天气 Web 应用程序

📣尾注:
想要获取更多数据结构相关的知识,你可以关注我:海拥,我希望你觉得这篇文章有帮助。

如果你看到这里,感谢你的阅读 🙂

💌 欢迎大家在评论区提出意见和建议!💌

如果你真的从这篇文章中学到了一些新东西,喜欢它,收藏它并与你的小伙伴分享。🤗最后,不要忘了❤或📑支持一下哦。