Topic description:
Try to write an efficient algorithm for deleting a minimum node in a singly linked list L with a head node (assuming that the minimum node is unique)
The idea of the answer is very clear, but I didn't expect it at first. The idea I thought of is as follows (more straight, not as advanced as the answer):
Ideas:
- The first thing to remember is that if we want to delete or insert an element in the singly linked list , we must write it down
被删除的元素的前驱结点
, because the successor node can be obtained from the predecessor node->next->next no matter how bad it is. So the precursor node is a must! - In this question, we need to constantly compare the data value of each node, and then record the predecessor of the current smallest node.
- So, my idea is to constantly compare p->next, then the predecessor node is p.
- And a q pointer needs to be used to track p (pointing to p), because p->next needs to be constantly compared, so p needs to move backward, and every time it is currently
最小的那个节点的前驱
recorded by the q pointer
Specific code (runnable):
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
LinkList Init(LinkList L){
int x;
L = (LinkList)malloc(sizeof(LNode));
LinkList r,s;
r = L;
printf("请输入元素:\n");
scanf("%d",&x);
while(x!= 999){
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s;
printf("请输入元素:\n");
scanf("%d",&x);
}
r->next = NULL;
return L;
}
void print(LinkList L){
LinkList p;
p = L->next;
while(p!= NULL) {
printf("%5d",p->data);
p = p->next;
}
printf("\n");
}
void Del_min(LinkList L){
LinkList p,q,r;
int min;
p = L;
min = p->next->data;
while(p->next != NULL){
if(p->next->data <= min){
min = p->next->data;
q = p;
}
p = p->next;
}
r = q->next;
q->next = r->next;
free(r);
print(L);
}
int main(){
LinkList L,L1;
L1 = Init(L);
printf("打印初始链表:\n");
print(L1);
printf("打印删除最小值之后的链表:\n");
Del_min(L1);
return 0;
}
Write the answer:
void Del_min(LinkList L){
LinkList p,q,r;
int min;
p = L;
min = p->next->data;
while(p->next != NULL){
if(p->next->data <= min){
min = p->next->data;
q = p;
}
p = p->next;
}
r = q->next;
q->next = r->next;
free(r);
}