Leetcode 21. Merge Two Sorted Lists (Easy) (cpp)

来源:互联网 发布:采集数据犯法吗 编辑:程序博客网 时间:2024/05/21 01:30

Leetcode 21. Merge Two Sorted Lists (Easy) (cpp)

Tag: Linked List

Difficulty: Easy


/*21. Merge Two Sorted Lists (Easy)Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two 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* dummy = new ListNode(-1);        for (ListNode* p = dummy; l1 != NULL || l2 != NULL; p = p -> next) {            if (l1 == NULL || l2 != NULL && l2 -> val < l1 -> val) {                p -> next = l2;                l2 = l2 -> next;            } else {                p -> next = l1;                l1 = l1 -> next;            }        }        return dummy -> next;    }};


0 0