首页 > 代码库 > [Leetcode] 21 - Merge Two Sorted Lists
[Leetcode] 21 - Merge Two Sorted Lists
原题链接:https://oj.leetcode.com/problems/merge-two-sorted-lists/
这道题用指针的指针实现,做法会非常简单干净。直接上代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode *head = NULL; ListNode **pp = &head; ListNode *p1 = l1; ListNode *p2 = l2; while (p1 && p2) { if (p1->val < p2->val) { *pp = p1; p1 = p1->next; } else { *pp = p2; p2 = p2->next; } pp = &(*pp)->next; } while (p1) { *pp = p1; pp = &(*pp)->next; p1 = p1->next; } while (p2) { *pp = p2; pp = &(*pp)->next; p2 = p2->next; } return head; } };
[Leetcode] 21 - Merge Two Sorted Lists
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。