Deletion of singly linked list: see ideas through pictures
The p pointer is used to find the position of the number x in the linked list, and the pre pointer always points to the previous position of the position pointed to by the p pointer
It's better to simulate it yourself on paper
Code:
#include<bits/stdc++.h>
using namespace std;
typedef struct Node
{
int value;
struct Node *next;
}node,*linkedlist;
linkedlist linkedlistdelete(linkedlist l,int x)
{
node *p=(node *)malloc (sizeof(node));
p=l->next; //The p pointer points to the first number of the linked list, and then the p pointer goes down
node *pre=(node *)malloc(sizeof(node)); //The pre pointer must be maintained, and the pre pointer always points to the previous node of the node pointed to by the p pointer
while (p->value!=x) //As long as the number of the node pointed to by the p pointer is not equal to x, the p pointer will go to Go down
{
pre=p;
p=p->next;
}
pre->next=p->next; //The program is here, indicating that the node with the number x has been found, and pre points to the front of this node A node, let the next node of the node be directly equal to the next node of the number equal to x node
free(p); //Release the node whose number is equal to x
return l;
}
Insert a number x into the singly linked list i position to see the idea through the picture
The function of the pre pointer is to reach the specified position in the linked list, that is, the i position p pointer (called the pointer here is not very accurate) is the newly added linked list structure
code
#include<bits/stdc++.h>
using namespace std;
typedef struct Node
{
int value;
struct Node *next;
}node,*linkedlist;
linkedlist linkedlistinsert(linkedlist l,int i,int x) //Pointer l points to The first address of the linked list, i represents the i position added to the linked list, x represents the number to be added
{
node *pre=(node *)malloc(sizeof(node)); //Define the pre pointer to find out the number of items in the linked list i position
pre=l->next; //At the beginning, let the pre pointer point to the first position of the linked list. Note: here is the assignment from address to address.
int index;
for(index=1;index<i-1;i++) //Through this for loop, pre can successfully point to the i position in the linked list
pre=pre->next; //Let the pre pointer point to the node that pre now points to The next node
node *p=(node *)malloc(sizeof(node)); //Create a new node
p->value=x;
p->next=pre->next; //Let the newly created node p point to the next node of the node at i position
pre->next=p; //The pre node (the node at the original i position) points to the newly created p node
return l;
}