#include<stdio.h>
#include<stdlib.h>
struct LB
{
int data;
struct LB *next;
};
struct LB *Create();
void Shu(struct LB *head);
struct LB *Delete(struct LB *head);
struct LB *Motive(struct LB *head);
int main()
{
struct LB *A;
printf("请输入链表结点元素值(输入-1回车结束输入):\n");
A=Create();
Shu(A);
// printf("删除最小元素结点后链表元素如下:\n");
// A=Delete(A); //删除最小元素值结点
printf("将最小元素结点移动到链表最前面后链表元素如下:\n");
A=Motive(A); //移动最小元素值结点
Shu(A);
return 0;
}
struct LB *Create()
{
struct LB *head=NULL,*p,*p1;
p=(struct LB *)malloc(sizeof(struct LB));
scanf("%d",&p->data );
p->next =NULL;
while(p->data !=-1)
{
if(head==NULL)
{
head=p;
p1=p;
}
else
{
p1->next =p;
p1=p;
}
p=(struct LB *)malloc(sizeof(struct LB));
scanf("%d",&p->data );
p->next =NULL;
}
return head;
}
void Shu(struct LB *head)
{
struct LB *p;
p=head;
while(p!=NULL)
{
printf("%-3d",p->data );
p=p->next ;
}
putchar('\n');
}
struct LB *Delete(struct LB *head) //思路大概就是边遍历边标志当前最小结点,遍历完就可以找到标志位然后删除释放即可,不过返回的结点要看你删除的是不是第一个节点
{
struct LB *p,*p1,*min,*pro; //换做有头结点的好删除一点 ,再用指针标注最小结点的前后位置方便遍历完直接删除
p=(struct LB *)malloc(sizeof(struct LB));
p->next =head;
p1=head;
int minn;
while(p1!=NULL)
{
if(p1==head)
{
minn=p1->data ;
pro=p;
min=p1;
}
else
{
if(p1->data <minn)
{
minn=p1->data ;
pro=p;
min=p1;
}
}
p=p->next ;
p1=p1->next ;
}
if(min==head) //表示要删除第一个结点
{
pro->next=min->next ;
free(min); //释放被删除结点
return pro->next ;
}
pro->next=min->next ;
free(min); //释放被删除结点
return head;
}
struct LB *Motive(struct LB *head) //思路大概是根删除有点像,标志出来,然后遍历完之后取出,然后让他变成第一个结点即可,so so easy!!
{
struct LB *p,*p1,*min,*pro; //不需要删除所以不用设置头结点
p=head;
p1=head->next ;
int minn;
minn=p->data ;
while(p1!=NULL)
{
if(p1->data <minn)
{
minn=p1->data ;
pro=p;
min=p1;
}
p=p->next ;
p1=p1->next ;
}
if(minn==head->data ) //表示是第一个结点,即不需要移动
return head;
pro->next =min->next ;
min->next =head;
return min;
}
试编写在带头结点的单链表中删除(一个)最小值结点的(高效)算法。void delete将链表中数据域值最小的那个链结点移到链表的最前面。
于 2022-11-11 15:27:45 首次发布