一.题目及剖析
https://leetcode.cn/problems/merge-two-sorted-lists/description/
二.思路引入
用指针遍历两个链表并实时比较,较小的元素进行尾差,然后较小元素的指针接着向后遍历
三.代码引入
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {struct ListNode *newHead, *newTail, *l1, *l2;newHead = newTail = (struct ListNode*)malloc(sizeof(struct ListNode));l1 = list1;l2 = list2;if(list1 == NULL)return list2;if(list2 == NULL)return list1;while(l1 && l2){if(l1->val > l2->val){newTail->next = l2;newTail = newTail->next;l2 = l2->next;}else{newTail->next = l1;newTail = newTail->next;l1 = l1->next;}}if(l1)newTail->next = l1;if(l2)newTail->next = l2;return newHead->next;
}