c语言链表排序交换节点的思想,链表的排序(交换指针指向)

本文介绍了一名学生在C语言实习中对链表进行选择排序的过程,探讨了直接交换节点元素与交换指针指向的不同方法,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本学期c语言实习,要用到链表的排序。虽说以前没用过,但还是花时间写了写。老师说排序的时候指针不变交换节点里面的元素,我觉得这道不如交换指针的指向来的干脆,因为如果按老师的方法来写,节点里的元素很多的话就废了==

#include

#include

#include

#include

using namespace std;

struct student

{

int a,b;

student *next;

};

int main()

{

student *q,*p,*h,*m,*temp;

h=NULL;

p=(student *)malloc(sizeof(student));

scanf("%d%d",&p->a,&p->b);

h=p;

q=p;

for(int i=0;i<5;i++)

{

p=(student *)malloc(sizeof(struct student));

q->next=p;

scanf("%d%d",&p->a,&p->b);

q=p;

}

q->next=NULL;

//=========================================================

//按元素b递增进行选择排序

int maxx=-99999;

for(p=h;p->next!=NULL;p=p->next)

{

if((p->next->b)>maxx)

{

maxx=(p->next->b);

q=p;

//

}

}

//printf("%d\n",maxx);

// printf("%d\n",q->next->b);

temp=q->next->next;

q->next->next=h->next;

h->next=temp;

temp=q->next;

q->next=h;

h=temp;

//printf("%d\n",h->b);

for(p=h;p->next->next!=NULL;p=p->next)

{

int maxx=-9999999;

for(q=p->next;q->next!=NULL;q=q->next)

{

if(q->next->b>maxx)

{

maxx=q->next->b;

m=q;

}

}

if(maxx>xp->next->b)

{

temp=p->next;

p->next=m->next;

m->next=temp;

if(m->next->next==NULL)

{

m->next->next=p->next->next;

p->next->next=NULL;

}

else

{

temp=p->next->next;

p->next->next=m->next->next;

m->next->next=temp;

}

}

}

//=============================================================

printf("\n\n");

for(p=h;p!=NULL;p=p->next)

{

printf("%d %d\n",p->a,p->b);

}

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值