leetcode---merge-two-sorted-lists---链表

来源:互联网 发布:centos 7.3 安装vftp 编辑:程序博客网 时间:2024/06/01 10: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.

/** * 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)            return l2;        if(!l2)            return l1;        ListNode *head = new ListNode(0);        ListNode *p = l1, *q = l2;        ListNode *pp = head;        while(p && q)        {            if(p->val < q->val)            {                pp->next = p;                p = p->next;                pp = pp->next;            }            else            {                pp->next = q;                q = q->next;                pp = pp->next;            }        }        if(p)            pp->next = p;        if(q)            pp->next = q;        return head->next;    }};
原创粉丝点击