Day008:merge two sorted lists

来源:互联网 发布:wcf 数据库 编辑:程序博客网 时间:2024/05/29 19:27

Problem:
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 *n1=l1,*n2=l2,*head=nullptr,*node=nullptr;        if(n1==nullptr||n2==nullptr) return (n1==nullptr?n2:n1);        if(n1->val>n2->val){            head=n2;            n2=n2->next;            }        else{            head=n1;            n1=n1->next;        }        node=head;        while(n1!=nullptr && n2!=nullptr){            if(n1->val>n2->val){                node->next=n2;                n2=n2->next;            }            else{                node->next=n1;                n1=n1->next;            }            node=node->next;        }        if(n1!=nullptr){            node->next=n1;        }        if(n2!=nullptr){            node->next=n2;        }        return head;    }};
0 0
原创粉丝点击