Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first
two lists.
双指针大法 解决
//
// MergeTwoSortedLists.c
// Algorithms
//
// Created by TTc on 15/6/18.
// Copyright (c) 2015年 TTc. All rights reserved.
//
/**
* 合并两个排序的列表
合并两个排序链表并返回它作为一个新的列表。
新列表应该由连接在一起的节点前两个列表。 (也必须是排序好的)
*/
#include "MergeTwoSortedLists.h"
#include "List.h"
#include <string.h>
#include <stdlib.h>
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
//
//}
/**
* 双指针大法,创建两个 指针(首尾指针 向中间扫描)
*
*/
ListElmt*
mergeTwoLists(ListElmt* l1, ListElmt* l2) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
if(l1 == NULL && l2 == NULL) return NULL;
ListElmt *head = NULL; //新构建的 list的 头节点
if(*(int *)(l1->data) > *(int *)(l2->data)) {
head = l2;
l2 = l2->next;
}
else {
head = l1;
l1 = l1->next;
}
ListElmt *tempnode = head; //中间临时变量
//遍历 两个 list;如果两个list的节点都不为空(可能两个list的长度不同)
while(l1 != NULL && l2 != NULL) {
if(*(int *)(l1->data) > *(int *)(l2->data)) {
tempnode->next = l2;
l2 = l2->next;
}
else {
tempnode->next = l1;
l1 = l1->next;
}
tempnode = tempnode->next;
}
//当两个list遍历完毕后(可能两个list的长度不同,长度较长的 list的 剩余部分追加)
if(l1 != NULL) {
tempnode->next = l1;
}
else {
tempnode->next = l2;
}
return head;
}
void
test_mergeTwoLists(){
List l1,l2;
list_init(&l1, free);
list_init(&l2, free);
int *data ,*data1;
int array[15] = {100,200,300,4000,5000,500,400,300,200,100};
int array1[5] = {10,9,8,7,6};
for (int i = 0; i< 10; i++) {
if ((data = (int *)malloc(sizeof(int))) == NULL)
return ;
*data = array[i];
if (list_ins_next(&l1, NULL, data) != 0) //逐个插入元素
return;
}
print_list(&l1);
for (int i = 0; i < 5; i++) {
if ((data1 = (int *)malloc(sizeof(int))) == NULL)
return ;
*data1 = array1[i];
if (list_ins_next(&l2, NULL, data1) != 0) //逐个插入元素
return;
}
print_list(&l2);
ListElmt *result = mergeTwoLists(list_head(&l1), list_head(&l2));
printf("result->val===%d\n",*(int *)result->data);
print_listNode(result);
}