Merge Two Sorted Lists

来源:互联网 发布:南京大学软件学院硕士 编辑:程序博客网 时间:2024/05/17 02:36

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*p=l1,*q=l2;        if(!l1)            return l2;        if(!l2)            return l1;        ListNode*res=new ListNode(0),*slo=res;        while(p&&q)        {            if(p->val<=q->val)            {                slo->next=p;                p=p->next;            }            else            {                slo->next=q;                q=q->next;            }            slo=slo->next;        }        if(p)            slo->next=p;        else if(q)            slo->next=q;        return res->next;    }};


0 0
原创粉丝点击