leetcode21题
方法一:使用递归,先将两个链表判空,然后使用递归比较大小并将大的节点放在后面
代码:
include "stdio.h"
#include "stdlib.h"
typedef struct ListNode{
int val;
struct ListNode *next;
}ListNode;
ListNode*mergeTwoLists(ListNode*list1, ListNode*list2){
if(list1 == NULL){
return list2;
}
if(list2 == NULL){
return list1;
}
if(list1-> val >= list2-> val){
list2-> next = mergeTwoLists(list1, list2-> next);
return list2;
}
list1-> next = mergeTwoLists(list1-> next, list2);
return list1;
}
int main() {
ListNode a;
ListNode b;
ListNode c;
ListNode d;
ListNode e;
ListNode f;
a.val = 1;
b.val = 4;
c.val = 6;
d.val = 0;
e.val = 5;
f.val = 7;
a.next = &b;
b.next = &c;
c.next = null;
d.next = &e;
e.next = &f;
f.next = null;
ListNode *l1 = &a;
ListNode *l2 = &d;
while(l1){
printf("%d ", l1-> val );
l1 = l1-> next;
}
printf("\n");
while(l2){
printf("%d ", l2-> val );
l2 = l2-> next;
}
ListNode*list = mergeTwoLists(&a, &d);
printf("\n" );
while (list) {
printf("%d ", list-> val );
list = list-> next;
}
return 0;
}
方法二:使用临时头节点,将大的节点放在前面,小的放在后面(暴力解法 )
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
typedef struct ListNode{
int val;
struct ListNode *next;
}ListNode;
ListNode*mergeTwo(ListNode*l1, ListNode*l2){
ListNode temp_head; //设置临时头节点temp_head
ListNode*pre = &temp_head; //使用pre指针指向temp_head
while (l1&&l2) {
if(l1-> val < l2-> val){//l1与l2同时不空时,对他们进行比较
pre-> next = l1;
l1 = l1-> next;
}else{
pre-> next = l2;
l2 = l2-> next;
}
pre = pre-> next;
}
if(l1){
pre-> next = l1;
}
if(l2){
pre-> next = l2;
}
return temp_head.next;
}
int main() {
ListNode a;
ListNode b;
ListNode c;
ListNode d;
ListNode e;
ListNode f;
a.val = 1;
b.val = 4;
c.val = 6;
d.val = 0;
e.val = 5;
f.val = 7;
a.next = &b;
b.next = &c;
c.next = null;
d.next = &e;
e.next = &f;
f.next = null;
ListNode *l1 = &a;
ListNode *l2 = &d;
while(l1){
printf("%d ", l1-> val );
l1 = l1-> next;
}
printf("\n");
while(l2){
printf("%d ", l2-> val );
l2 = l2-> next;
}
ListNode*list = mergeTwo(&a, &d);
printf("\n" );
while (list) {
printf("%d ", list-> val );
list = list-> next;
}
return 0;
}