华米面试题,链表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;
}