描述:
试编写在带头结点的单链表中删除(一个)最小值结点的(高效)算法。
void delete(Linklist &L)
输入:
输入一个整数 n,代表单链表的长度。
再输入 n 个整数,代表每个结点的值。
输出:
输出删除后的单链表的值。
输入样例
5
6 7 4 1 5
输出样例
6 7 4 5
Code:
#include "stdio.h"
#include "stdlib.h"
typedef struct node
{
int data;
struct node *next;
}node;
typedef struct
{
int length;
struct node *next;
}Linklist;
void delete(Linklist **L)
{
node *min,*minpre,*p,*ppre;
ppre=(*L),p=(*L)->next;
minpre=ppre,min=minpre->next;
while (p)
{
if(p->data<min->data)
{
min=p;
minpre=ppre;
}
ppre=p;
p=p->next;
}
minpre->next=min->next;
free(min);
}
int main(void )
{
Linklist *L=(Linklist *) malloc(sizeof (Linklist));
node *p,*tail;
L->next=p=tail=NULL;
scanf("%d",&L->length);
while (L->length)
{
p=(node *)malloc(sizeof (node));
scanf("%d",&p->data);
if(!L->next)
{
L->next=p;
}
else
{
tail->next=p;
}
p->next=NULL;
tail=p;
L->length--;
}
delete(&L);
p=L->next;
while (p)
{
printf("%d ",p->data);
p=p->next;
}
return 0;
}