[Leetcode]Merge Two Sorted Lists

来源:互联网 发布:linux安装glibc2.14 编辑:程序博客网 时间:2024/05/30 05:13

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:    /*algorithm        two pointer, merge to target list        time O(m+n) space O(1)    */    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {            ListNode* head = NULL,*tail;            while(l1 && l2){                if(l1->val < l2->val){                    if(!head)head = l1;                    else tail->next = l1;                    tail = l1;                    l1 = l1->next;                                    }else{                    if(!head)head = l2;                    else tail->next = l2;                    tail = l2;                    l2 = l2->next;                                    }            }            while(l1){                if(!head)head = l1;                else tail->next = l1;                tail = l1;                l1 = l1->next;            }            while(l2){                if(!head)head = l2;                else tail->next = l2;                tail = l2;                l2 = l2->next;            }            return head;    }};


0 0
原创粉丝点击