leetcode - Merge Two Sorted Lists

来源:互联网 发布:印度 网络空间作战部队 编辑:程序博客网 时间:2024/04/30 11:37

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.

分析:注意合并后的第一个节点

class Solution {public:    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {        if(l1 == NULL)return l2;        if(l2 == NULL)return l1;        ListNode *head = NULL;        ListNode *temp;                if(l1->val > l2->val)        {            head = l2;            l2 = l2->next;         }        else        {            head = l1;            l1 = l1->next;        }        temp = head;                while((l1)&&(l2))        {            if(l1->val > l2->val)            {                temp->next = l2;                temp = l2;                l2 = l2->next;            }            else            {                temp->next = l1;                temp = l1;                l1 = l1->next;            }        }                if(l1)temp->next = l1;        else temp->next = l2;                return head;    }};


0 0
原创粉丝点击