Anyone who has studied data structure knows that if you want to insert an operation on a singly linked list , you generally need to find the previous node to be inserted and perform a post-insertion operation, that is,
s->next = p->next; //s为插入结点,p为前一个结点
p->next = s;
But if a node p is required, and a node s is required to be inserted before the node p, what should we do? We cannot find the pointer of the node before the node p, so it is impossible to proceed according to the normal idea. inserted.
At this time, we can change our thinking, steal the day, solve the problem cleverly, insert the node s into the node p , and then exchange the values of the nodes s and p , thus completing the pre- insertion operation. Re-exchange, but it is still a pre-plug operation logically .
My own analysis chart, hehe
Implementation of C language code
//已知链表 L 为单链表, 要求在第i个结点 前插结点s
bool PreInsert(LinkList &L, int i){
if(i < 1 || i > Length(L)) //仅可以插入到第一个结点和最后一个结点之前
return false;
int is_insert = 0, temp;
printf("请输入要插入的数据:\n"); //生成要插入的数据结点
scanf("%d", &is_insert);
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = is_insert;
s->next = NULL;
LNode *p = GetElem(L, i); //找到第i个位置的结点
s->next = p->next; //逻辑上实现前插操作
p->next = s;
temp = s->data;
s->data = p->data;
p->data = temp;
return true;
}
Running screenshots: