将链表链接并且对链表排序(通过插入和删除函数实现
2016-04-16 22:13
459 查看
#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; } }
相关文章推荐
- linux上操作注意事项
- hdu 2871 线段树(各种操作)
- hdu 2871 线段树(各种操作)
- 设计模式
- 【Linux多线程同步】条件变量
- linux下ssh的一些基本配置
- 内网ip打洞-----p2p实现原理
- http://blog.csdn.net/rongyongfeikai2/article/details/41659353
- iOS MJRefresh下拉刷新 上拉加载(可添加gif图版) 小结
- Android 开发之集成百度地图的定位与地图展示
- hdu--5665--Lucky
- 在Java的JDBC使用中设置事务回滚的保存点的方法
- C#反射实用技术
- Atitit .h5文件上传
- 软工UML学习札记
- 一个很好的仿微博消息浏览功能的Demo
- JS截取字符串substr和substring方法的区别
- Atitit .h5文件上传
- C#与JAVA的区别
- iOS App图标和启动画面尺寸