您的位置:首页 > 编程语言 > C语言/C++

链表排序问题

2015-08-26 10:36 316 查看
写一个函数 它获取两个传引用的参数,两个参数都是指针变量,分别指向两个链表的表头 而且两个链表都由int类型的值构成,假定两个链表已经排好序了,位于表头的数子是最小的数字,然后从小到大依次排列,函数返回一个新的链表的表头的指针。新链表包含原来两个链表的所有的节点,而且同样按从小到大的顺序排列。

#include<iostream>

#include<stdlib.h>

#include<stdio.h>

#include"nicai.h"

#include<math.h> 

#include<string>

#include<algorithm>

//#include<cmath>

using namespace std;

struct Node

{

int data;

Node *link;

};

Node* thired;

typedef Node*  NodePtr;

void head_sert(NodePtr& head,int number)

{

NodePtr temp;

temp=new Node;

temp->data=number;

temp->link =head;

head=temp;

}

void paixu(NodePtr& a,NodePtr&b)

{

thired=new Node;
thired->data =0;

thired->link =NULL;

while((a->link !=NULL)&&(b->link!=NULL))

{if(a->data>b->data)

{

NodePtr temp;

temp=new Node;

temp->data=a->data;

temp->link =thired;

thired=temp;

a=a->link ;

}

else

{

NodePtr temp;

temp=new Node;

temp->data=b->data;

temp->link =thired;

thired=temp;

b=b->link ;

};

};

if(a->link ==NULL)

{

NodePtr temp;

temp=new Node;

temp->data=b->data;

//temp->link =thired;

thired=temp;

}

if(b->link ==NULL)

{

NodePtr temp;

temp=new Node;

temp->data=a->data;

temp->link =thired;

thired=temp;

}

while(thired->link !=NULL)

{

cout<<thired->data;

thired=thired->link ;

}

}

void main()

{

Node* first;

first=new Node;

first->link =NULL;

Node*  second;

second=new Node;

second->link =NULL;

for(int i=1;i<8;i=i+2)

{

head_sert(first,i);

};

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

{

head_sert(second,i);

};

paixu(first,second);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 链表