编写带头结点的单链表L中删除一个最小值结点的高效算法
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode * next;
}LNode ,*LinkList;
/*编写带头结点的单链表L中删除一个最小值结点的高效算法*/
LinkList delete_min(LinkList &L){
LNode *pre=L,*p=pre->next;
LNode *minpre=pre,*minp=p;
while(p!=NULL){
if(p->data<minp->data){
minpre=pre;
minp=p;
}
p=p->next;
pre=pre->next;
}
minpre->next=minp->next;
free(minp);
return L;
}
LinkList createLinkListStern(LinkList &L){
ElemType x,n;
L=(LinkList)malloc(sizeof(LNode));
if(L==NULL){
printf("内存分配失败");
}
L->next=NULL;
printf("输入单链表的长度:");
scanf("%d",&n);
LNode *s,*r=L;//r指向尾指针
for(int i=0;i<n;i++){
printf("输入第%d个元素:",(i+1));
scanf("%d",&x);
s=(LinkList)malloc(sizeof(LNode));
s->data=x;
r->next=s;
r= s;
}
r->next=NULL;
return L;
}
/*
遍历展示单链表的值
*/
void display(LinkList &L){
LinkList p;
printf("输出单链表元素:\n");
for(p=L->next;p!=NULL;p=p->next){
int i=1;
printf("第%d个元素为%d\n",i++,p->data);
}
}
int main(){
LNode *L;
createLinkListStern(L);
display(L);
printf("删除最小值");
delete_min(L);
display(L);
return 0;
}
截图: