【LeetCode】Merge Two Sorted Lists

来源:互联网 发布:奢侈品软件哪个最好 编辑:程序博客网 时间:2024/06/05 02:19

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.

思路:链表的归并,思路每次将小者取出,直到NULL,将剩余的放到链表末尾即可。

/** * 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) {        if(NULL == l1)return l2;        if(NULL == l2)return l1;        ListNode *pre = NULL;        ListNode *ret = NULL;        if(l1->val < l2->val){            pre=l1;            ret=l1;            l1=l1->next;        }else{            pre=l2;            ret=l2;            l2=l2->next;        }        while(NULL != l1 && NULL != l2){            if(l1->val < l2->val){                pre->next=l1;                pre=l1;                l1=l1->next;            }else{                pre->next=l2;                pre=l2;                l2=l2->next;            }        }        if(NULL != l1)pre->next=l1;        if(NULL != l2)pre->next=l2;        return ret;    }};



0 0