Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Given a single list and a location, deletes a list node at the given location.

Example:

Enter: position =1, list =8->2->3->1->7Output: linked list =8->3->1->7Enter: position =0, list =8->2->3->1->7Output: linked list =2->3->1->7
Copy the code

If the node to be deleted is the root node, delete it directly. To delete an intermediate node, we must have a pointer to the node before the node we want to delete. Therefore, if the position is not zero, we loop position-1 times and get a pointer to the previous node.

Here is the implementation of the above ideas.

#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(a); 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(a)
{
	Node* head = NULL;

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

	cout << "List created:";
	printList(head);
	deleteNode(&head, 4);
	cout << "\n position 4 deleted linked list:";
	printList(head);
	return 0;
}
Copy the code

Output:

Create linked list:8 2 3 1 7location4Deleted linked list:8 2 3 1 
Copy the code

🥇 past quality articles

Teach you make a small game gobang in Java Single AI minesweeping game using the python list of singly linked list data structure is introduced | first set of singly linked list data structure in the linked list and array | second singly linked list data structure of chain table insert | | delete nodes of the third set of singly linked list data structure in the fourth set Create a Simple Calculator using Java AWT Cool Black theme analog clock using HTML, CSS and JavaScript Make a great weather Web using HTML, CSS, JS and apis The application

📣 Endnote: For more information on data structures, you can follow me: Haiyong, I hope you found this article helpful.

If you see this, thank you for reading 🙂

💌 welcomes your comments and suggestions in the comments section! 💌

If you really learn something new from this article, like it, bookmark it and share it with your friends. 🤗 and finally, don’t forget ❤ or 📑.