合并有序链表,利用两个双指针分别指向两个链表头部,每次比较两个指针指向结点的值,取较小的一个存入结果链表,代码如下:
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param l1 ListNode类 * @param l2 ListNode类 * @return ListNode类 */ ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { // write code here ListNode *dummyHead = new ListNode(0); ListNode *cur = dummyHead; while(l1 && l2) { if(l1->val < l2->val) { cur->next = l1; l1 = l1->next; } else { cur->next = l2; l2 = l2->next; } cur = cur->next; } while(l1) { cur->next = l1; l1 = l1->next; cur = cur->next; } while(l2) { cur->next = l2; l2 = l2->next; cur = cur->next; } return dummyHead->next; } };
全部评论
(0) 回帖