两个链表的合并排序

华米面试题,链表A数据为1,3,5;链表数据B数据为2 ,4 ,6;变成数据为123456的链表;


自己在VS写出来的,编译通过;


#include<iostream>
using namespace std;


typedef struct Node{
	int data;
	struct Node *next;
}node;



int Length(node *head)
{
	int len=0;
	node *p1=head;
	while(p1!=NULL)
	{
		p1=p1->next ;
		len++;
	}
	return len;
}


node *ListSort(node *head)
{
	
	
	if(head==NULL||head->next ==NULL)
		return head;


	int temp;
	node *p1=head;
	node *p2;
	int i ,j;
	
	int len=Length(head);

    for(i=1;i<len;i++)
	{
		p1=head;
		
		for(j=1;j<len-i;j++)
		{
			p2=p1->next;
			if(p1->data > p2->data )
			{
				temp=p1->data;
			     p1->data =p2->data ;
				 p2->data =temp;
			}
			
			p1=p2;
		}
	}

			return head;

}


void ListPrintf(node *head)
{
	node *p=head;
	
	while(p!=NULL)
	{
		cout<<p->data<<" ";
		p=p->next ;
	}
}


// 链表的测长



node *CreateList(int n)
{
	node *p1,*p2;
	node *head;
	int x;
	
	head=(node*)malloc(sizeof(node));

	p1=head;
	
		while(n--)
		{
			p2=(node*)malloc(sizeof(node));
			cout<<" input data: ";
			cin>>x;
			p2->data =x;
			p1->next =p2;
			p1=p2;
		}
	
	head=head->next;    //第一个有数据的给头指针;
	p1->next=NULL;
	
	return head;
}

node *ListConnect(node *head1,node *head2)
{
	node *p1,*p2;
	p1=head1;
	while((p2=p1->next )!=NULL)
		p1=p2;
	p1->next =head2;

	return head1;
}





int main(int argc,char **argv)
{
	node *head1,*head2;
	int n=3;

	head1=CreateList(n);
	ListPrintf(head1);
	cout<<endl;
	

	head2=CreateList(n);
	ListPrintf(head2);
	cout<<endl;

	head1=ListConnect(head1,head2);
	ListPrintf(head1);
	cout<<endl;

	head1=ListSort(head1);
	ListPrintf(head1);
	cout<<endl;


	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值