您的位置:首页 > 其它

将两个有序链表合并成一个有序链表——搜狐畅游笔试题归来

2010-10-17 15:09 323 查看
合并两个有序链表

递归实现:

①算法思想:

递归终止条件:若head1为空,返回head2指针(head);若head2为空,返回head1指针(head)

递归过程:

(1)若head1->data>head2->data; head 指针应该指向head2所指向的节点,而且head->next应该指向head1和head2->next两个链表的合成序列的头指针;

(2)否则head 指针应该指向head1所指向的节点,而且head->next应该指向head->next和head2两个链表的合成序列的头指针;

②实现代码(C++):

#include <iostream>
using namespace std;

/*节点的类定义*/
class Node
{
public:
int data;
Node * next;
Node(int data)
{
this->data=data;
}
};

/*链表的类定义*/
class LinkedList
{
public:
Node * head;

/*用一个整形数组作为参数的构造函数*/
LinkedList(int array[])
{
head=new Node(array[0]);
Node * temp=head;
int i;
for(i=1;i<3;i++)
{
temp->next=new Node(array[i]);
temp=temp->next;
}
temp->next=NULL;
}
};

/*递归的合并两个有序链表*/
Node * mergeLinkedList(Node * head1,Node * head2)
{
Node *p=NULL;
if(head1==NULL&&head2==NULL)
return p;
else if(head1==NULL)
return head2;
else if(head2==NULL)
return head1;
else
{
if(head1->data < head2->data)
{
p = head1;
p->next = mergeLinkedList(head1->next,head2);
}
else
{
p = head2;
p->next = mergeLinkedList(head1,head2->next);
}
return p;
}
}

/*打印链表的所有元素*/
void printList(Node * head)
{
Node * temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}

int main()
{
int array1[3]={2,5,8};
int array2[3]={1,6,7};

/*构造两个有序链表--list1和list2*/
LinkedList list1(array1);
LinkedList list2(array2);

/*递归的将这两个有序链表合并成一个有序链表*/
Node * new_head=mergeLinkedList(list1.head,list2.head);

/*打印有序链表*/
printList(new_head);

return 0;
}

实现memmove函数

#include <stdio.h>

/*函数功能与memmove相同。*/
void * Mymemmove(void * dest,const void * src,size_t count)
{
if(dest==NULL||src==NULL)
return NULL;

char * dest_p=(char *)dest;
char * src_p=(char *)src;

/*目标地址小于源地址,从前向后复制*/
if(dest<src)
{
while(count--)
*dest_p++=*src_p++;
}

/*目标地址大于源地址,从后向前复制*/
else if(dest>src)
{
dest_p+=count-1;
src_p+=count-1;
while(count--)
*dest_p--=*src_p--;
}
return dest;
}

void main()
{
char src[6]={'a','b','c','d','e','f'};
Mymemmove(&src[2],src,4);

/*打印源字符串*/
int i;
for(i=0;i<6;i++)
printf("%c",src[i]);
printf("/n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐