您的位置:首页 > 其它

链表的排序(交换指针指向)

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

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐