Merge Two Sorted Lists

来源:互联网 发布:2017下半年网络流行词 编辑:程序博客网 时间:2024/05/29 03:42

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) {        if(l1 == NULL)            return l2;        if(l2 == NULL)            return l1;        if(l1->val > l2->val)//l1的首个元素保持最小            swap(l1, l2);        ListNode *p = l1, *q = l2, *pre;        while(p && q){            if(p->val <= q->val){                pre = p;                p = p->next;            }            else{                ListNode *tmp = new ListNode(q->val);                tmp->next = pre->next;                pre->next = tmp;                pre = pre->next;                q = q->next;            }        }        if(q)            pre->next = q;        return l1;    }};
0 0
原创粉丝点击