LeetCode—Merge Two Sorted Lists

来源:互联网 发布:客户信息管理系统mac 编辑:程序博客网 时间:2024/06/07 23:04

题目:

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(l2==NULL)                return l1;             if(l1==NULL)                return l2;            ListNode *p, *q,*r,*head;        p = l1;        q = l2;        head=NULL;        if(p->val <= q->val)        {                  head = p;                  p = p->next;              }            else            {                  head = q;                  q = q->next;              }              r = head;          while (p&&q)        {        if (p->val <= q->val)        {        r->next = p;        p=p->next;        }        else        {        r->next =q;        q=q->next;        }        r=r->next;        }             if(p==NULL)                {                   r->next=q;                }                if(q==NULL)                {                   r->next=p;                }        return head;    }};


0 0
原创粉丝点击