题目:将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所
有节点组成的。 如下图所示:
思路:首先确定链表的头,再依次将链表结点链接在链表的尾部:
代码:
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
if (list1 == NULL) {
return list2;
}
if (list2 == NULL) {
return list1;
}
struct ListNode* newHead = NULL; // 新链表的头节点
struct ListNode* cur = NULL; // 新链表的当前节点
//确定新链表的头
if (list1->val <= list2->val) {
newHead = list1;
list1 = list1->next;
} else {
newHead = list2;
list2 = list2->next;
}
cur = newHead;
while (list1 != NULL && list2 != NULL) {
if (list1->val <= list2->val) {
cur->next = list1;
list1 = list1->next;
} else {
cur->next = list2;
list2 = list2->next;
}
cur = cur->next;
}
if (list1 != NULL) {
cur->next = list1;
} else {
cur->next = list2;
}