将两个升序链表合并成为一个新的链表并且返回。
示例: 链表1: 1->3->5
链表2: 2->4->6->7->8
输出新链表:1->2->3->4->5->6->7->8
思路:同时遍历两个链表,比较当前遍历到的节点的数据大小,把小的那个节点连接到新的链表中,当其中一条链表遍历结束,说明未结束的链表的剩余的所有节点都比已经结束的链表的所有节点大,此时让新链表连接未结束的链表即可。
代码:
typedef struct Node
{
int data;
struct Node* next;
}node;
//合并代码
node * list_hebing(node* head1,node *head2)
{
node *list1 = head1->next;
node *list2 = head2->next;
node *newlist = (node *)malloc(sizeof(node));
node *tail = newlist;
while((list1 != NULL) && (list2 != NULL))
{
if(list1->data <= list2->data)
{
tail->next = list1;
list1 = list1->next;
}
else
{
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}
tail->next = (NULL == list1? list2 : list1);
return newlist;
}