21. 合并两个有序链表
做法1:
构建虚拟头节点,而后双指针做法。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { ListNode* head = new ListNode(-1); ListNode* cur = head; while(list1 != nullptr && list2 != nullptr){ if(list1->val <= list2->val){ cur->next = list1; cur = cur->next; list1 = list1->next; } else{ cur->next = list2; cur = cur->next; list2 = list2->next; } } while(list1 != nullptr){ cur->next = list1; cur = cur->next; list1 = list1->next; } while(list2 != nullptr){ cur->next = list2; cur = cur->next; list2 = list2->next; } return head->next; } };
做法2:
迭代。那么最终返回的是哪一个节点呢?是两个链表最开始节点中小的那个节点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { if(list1 == nullptr) return list2; if(list2 == nullptr) return list1; if(list1->val <= list2->val){ list1->next = mergeTwoLists(list1->next, list2); return list1; } list2->next = mergeTwoLists(list1, list2->next); return list2; } };
标签:ListNode,21,val,list1,next,链表,有序,list2,cur From: https://www.cnblogs.com/luxiayuai/p/17278105.html