同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。
此题测验的是链表 ( Linked List ) ,把两个 Linked List 依照大小排序,串接在一起,并回传串接完的 Linked List。
题目与范例如下
Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: l1 = [], l2 = []
Output: []
Example 3:
Input: l1 = [], l2 = [0]
Output: [0]
Constraints:
The number of nodes in both lists is in the range [0, 50].
-100 <= Node.val <= 100
Both l1 and l2 are sorted in non-decreasing order.
解题策略为透过 l1 储存要回传的 Linked List,每次回圈依序比较 l1 跟 l2 的值,把 l2 的值依序连接到 l1 上,最后回传 l1。
下方为我的代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1 == NULL)
return l2;
else if(l2 == NULL)
return l1;
else{
struct ListNode *ptr,*Fptr;
ptr = l1;
Fptr = ptr;
while(l2!=NULL){
if(ptr->val > l2->val){
struct ListNode *temp = l2;
l2 = temp->next;
temp->next = ptr;
if(ptr == l1){
l1 = temp;
Fptr = l1;
}
else{
Fptr->next = temp;
Fptr = temp;
}
}
else{
if(ptr->next!=NULL){
if(Fptr == ptr){
}
else{
Fptr = Fptr->next;
}
ptr = ptr->next;
}
else{
ptr->next = l2;
l2 = NULL;
}
}
}
return l1;
}
}
下方为时间与空间之消耗
Runtime: 0 ms, faster than 100.00% of C online submissions for Merge Two Sorted Lists.
Memory Usage: 6 MB, less than 99.18% of C online submissions for Merge Two Sorted Lists.
451

被折叠的 条评论
为什么被折叠?



