将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
提示:
两个链表的节点数目范围是 [0, 50]
-100 <= Node.val <= 100
l1 和 l2 均按 非递减顺序 排列
题解:
由于没有看清题(没看到两链表都是非降序排列),解法有点麻烦,后面一种方法运用递归来求解,代码行数大减,解决问题前还是得先思考思考有没有什么便捷的方法,不能一上来就暴力求解
思路1如下:
1.考虑特殊情况,有一个链表为空,则返回另一个链表即可
2.一般情况:计算节点数,并将两个链表的值都放到一个数组里面
3.比较大的那一个链表拿来重新装值(设置一个慢指针,指向上一个节点,最后退出while时,令该节点等于慢指针所在的节点),接着新开节点(这里设置了一个flag标志是不是第一次开节点,如果是第一次,那么就要将),最后记得另最后开的一个节点指向NULL(记得开一个根节点指向表头)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
struct ListNode* cont1 = list1;
struct ListNode* cont2 = list2;
struct ListNode* head;
struct ListNode* fwd;
struct ListNode* newpt;
char length1 = 0;
char length2 = 0;
char length3 = 0;
char temp;
char num[101] = {0};
char flag = 0;
/*
**计算节点数
*/
if(list1 == NULL)
return list2;
if(list2 == NULL)
return list1;
while(cont1){
num[length1] = cont1->val;
length1++;
cont1 = cont1->next;
}
while(cont2){
num[length1 + length2] = cont2->val;
length2++;
cont2 = cont2->next;
}
length3 = length1 + length2 ;
/*
**对num排序
*/
for(char i = 0; i < length3 - 1; i++)
for(char j = i + 1; j < length3; j++){
if(num[i] > num[j]){
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
/*
**为新节点配置内存
*/
if(length1 >= length2){
head = list1;
for(char i = 0; i < length1 ; i++){
list1->val = num[i];
fwd = list1;
list1 = list1->next;
}
list1 = fwd;
for(char i = length1 ; i < length3; i++){
if(flag == 0){
newpt = (struct ListNode*)malloc( sizeof(struct ListNode));
list1->next = newpt;
flag = 1;
}
else{
newpt->next = (struct ListNode*)malloc( sizeof(struct ListNode));
newpt = newpt->next;
}
newpt->val = num[i];
}
newpt->next = NULL;
}
else{
head = list2;
for(char i = 0; i < length2; i++){
list2->val = num[i];
fwd = list2;
list2 = list2->next;
}
list2 = fwd;
for(char i = length2 ; i < length3; i++){
if(flag == 0){
newpt = (struct ListNode*)malloc( sizeof(struct ListNode));
list2->next = newpt;
flag = 1;
}
else{
newpt->next = (struct ListNode*)malloc( sizeof(struct ListNode));
newpt = newpt->next;
}
newpt->val = num[i];
}
newpt->next = NULL;
}
return head;
}
思路2如下:
运用递归思想,因为两个链表都是有序的,只要处理到有一个为空,则只需要将其最后一个节点指向另一个链表待处理的那个节点,再返回最先为空的链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
if(list1 == NULL)
return list2;
if(list2 == NULL)
return list1;
/*
**list1和list2的值比较大小,运用递归,只要有一个为空,则返回先没了的即可
*/
if(list1->val <= list2->val){
list1->next = mergeTwoLists(list1->next, list2);
return list1;
}
else{
list2->next = mergeTwoLists(list1, list2->next);
return list2;
}
}