用类的形式用链表排序

这里为了简单突出类,链表,我没有封装,假定两个链表已经排好序了,位于表头的数子是最小的数字,然后从小到大依次排列,函数返回一个新的链表的表头的指针。新链表包含原来两个链表的所有的节点,而且同样按从小到大的顺序排列。

代码如下:

nicai.h

namespace linkedlistofclasses
{


class nicai
{
private:

public:
nicai *getlink();
int getdata();
int data;
void setlinklist();
nicai(int number,nicai *next);


nicai* link;


};


nicai* nicai::getlink()
{
return link;


}


typedef nicai* nicaiptr;


int nicai::getdata ()
{

return data;
}


}
 
 
 
 diliuci.cpp


#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include"nicai.h"
#include<math.h> 
#include<string>
#include<algorithm>
//#include<cmath>
using namespace std;


using namespace linkedlistofclasses;
nicai::nicai(int value,nicai *next)
{
data=value;
link=next;




}
void setlinklist(nicaiptr& a,int number)
{
nicaiptr temp;


temp=new nicai(number,a);


a=temp;




};
void main()
{
nicaiptr first;
nicaiptr second;
first=new nicai(0,NULL);
second=new nicai(0,NULL);
for(int i=1;i<8;i=i+2)
{


setlinklist(first,i);


};
for(int i=2;i<9;i=i+2)
{


setlinklist(second,i);


}


nicaiptr thired;
thired=new nicai(0,NULL);
while((first->link!=NULL)&&(second->link !=NULL))
{
if(first->data >second->data )
{


nicaiptr temp;
temp=new nicai(0,NULL);
temp->data =first->data ;
temp->link=thired;
thired=temp;
first=first->link;

}
else
{

nicaiptr temp;
temp=new nicai(0,NULL);
temp->data =second->getdata ();
temp->link=thired;
thired=temp;
second=second->link;




};
if(first->link==NULL)//当first与second有一个事先为空是,把另外一个的data赋给thired;
{
nicaiptr temp;
temp=new nicai(0,NULL);
temp->data=second->data;
temp->link =thired;
thired=temp;



}
if(second->link ==NULL)
{
nicaiptr temp;
temp=new nicai(0,NULL);
temp-> data=first->data ;
temp->link =thired;
thired=temp;




}





}


while(thired->link!=NULL)


{
cout<<thired->data ;
thired=thired->link;



}






}




















 
 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值