您的位置:首页 > 其它

将链表链接并且对链表排序(通过插入和删除函数实现

2016-04-16 22:13 405 查看
#include<stdio.h>
#include<stdlib.h>
4000
//#pragma pack (1)

struct stu
{
int ID;
int score;
struct stu *next;
};
struct stu *SortList(struct stu *pHead,int sum);
struct stu *pDelete(struct stu* pHead,struct stu *pNow);
struct stu *pInsert(struct stu* pHead,int n,struct stu*pt);
void scan(struct stu *pHead);

int main(int argc,const char *argv[])
{
stu *p1,*p2,*head1,*head2,*mid1,*mid2;
int sum;
int N,M;
int t=1;
scanf("%d%d",&N,&M);
p1=(struct stu*)malloc(sizeof(struct stu));
while(t<=N)
{

if (t==1)
{
scanf("%d%d",&p1->ID,&p1->score);
head1=p1;
head1->next=NULL;
}
else
{
mid1=p1;
p1=(struct stu*)malloc(sizeof(struct stu));
mid1->next=p1;
scanf("%d%d",&p1->ID,&p1->score);
p1->next=NULL;
}
t++;
}

p2=(stu*)malloc(sizeof(stu));

t=1;
while(t<=M)
{

if (t==1)
{
scanf("%d%d",&p2->ID,&p2->score);
head2=p2;
head2->next=NULL;
}
else
{

mid2=p2;
p2=(struct stu*)malloc(sizeof(struct stu));
mid2->next=p2;
scanf("%d%d",&p2->ID,&p2->score);
p2->next=NULL;
}
t++;
}
p1->next=head2;
sum=N+M;
head1=SortList(head1,sum);
scan(head1);

return 0;
}

struct stu *SortList(struct stu *pHead,int sum)//节点排序 返回一个头节点指针
{
int min,t=1,i;
struct stu *temp,*pt,*p;

while (sum)
{
temp=pHead;
i=1;
while (i<t)
{
temp=temp->next;
i++;
}

p=temp;
min=p->ID;
pt=temp;
while (p!=NULL)
{
if(min>p->ID)
{
min=p->ID;
pt=p;
}
p=p->next;
}
if (pt==temp)
{
break;
}
else
{
pHead=pDelete(pHead,pt);
pHead=pInsert(pHead,t,pt);
}
t++;

sum--;
}
return pHead;
}

struct stu *pDelete(struct stu* pHead,struct stu *pNow)//删除节点
{
struct stu *p,*forw;
p=pHead;
while(p!=NULL)
{

if(pHead==pNow)
{
pHead=p->next;
break;
}
else if(p==pNow&&p->next==NULL)
{
forw->next=NULL;
}
else if(p==pNow)
{
forw->next=p->next;
break;
}

forw=p;
p=p->next;
}
return pHead;

}

struct stu *pInsert(struct stu * pHead,int n,struct stu *pt)//需要插入的节点的位置
{
int i=1;
struct stu*p,*forw;
p=pHead;
forw=pHead;
while (i<=n)
{
if(n==1)
{
pt->next=pHead;
pHead=pt;
break;
}

else if(i==n)
{
forw->next=pt;
pt->next=p;
break;

}
forw=p;
p=p->next;
i++;
}
return pHead;

}
void scan(struct stu *pHead)//遍历节点
{
struct stu *p;
p=pHead;
while (p!=NULL)
{
printf("%d %d\n",p->ID,p->score);
p=p->next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: