难度简单2394收藏分享切换为英文接收动态反馈
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 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
均按 非递减顺序 排列
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* ret = newnode;
while(list1 && list2){
if(list1 -> val < list2 -> val){
newnode -> next = list1;
list1 = list1 -> next;
}
else{
newnode -> next = list2;
list2 = list2 -> next;
}
newnode = newnode -> next;
}
if(list2){
newnode -> next = list2;
}
else{
newnode -> next = list1;
}
//newnode -> next = list1 == NULL ? list2 : list1;
return ret -> next;
}
记录一下对这个题的最基层的理解:首先有一点是,其实这个题里的newnode list1 list2等等都是节点(结构体)的指针,每当传递他们时,都是传的对应节点的地址,而使用newnode->xx list1->xx list2->xx 时也都是通过这个节点的地址去访问对应的内存区域(里面存储着一个数据,和另一个节点的地址)。
所以,创建一个新的节点,将这个节点的next作为返回值,每次比较list1和list2对应值的大小,将较小者的地址,即list1或list2本身传递给newnode的next,然后将他们本身改为他们的next。临时加一个例子吧:链表1为1 3 5 链表2为 2 4 6 则传递1的地址作为newnode的next之后,将list1改为data为3的那个节点的地址,然后比较3和2。此时2较小,则newnode->next改为data为2的那个节点的地址。其实这里newnode就是data为1的那个节点的地址,此时改了之后,1就会指向2。而这里不会出现错误的原因是,在1指向2之前,list1已经改为list1的next了。
over
递归版本
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
if(list1 == NULL)
return list2;
if(list2 == NULL)
return list1;
if(list1 -> val < list2 -> val)
{
list1 -> next = mergeTwoLists(list1 -> next, list2);
return list1;
}
else
{
list2 -> next = mergeTwoLists(list1, list2 -> next);
return list2;
}
}