leetcode_Merge Two Sorted Lists _简单

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.


题目就是合并两个有序的链表,具体方法就是:直接操作两个链表的各个指针域,使得最后两个链表连成一个有序的链表即可,其中主要用到了3个指针,p,cur1,cur2


/**
 * 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,*cur1,*cur2,*res;
        if(NULL==l1)//特殊情况
            return l2;
        else if(NULL==l2)//特殊情况
            return l1;
        else//一般情况
        {
            cur1=l1;
            cur2=l2;
            if((*cur1).val<(*cur2).val)
            {
                p=cur1;
                cur1=cur1->next;
            }
            else
            {
                p=cur2;
                cur2=cur2->next;
            }
            res=p;//保存头结点,备份用于返回
            while(cur1!=NULL && cur2!=NULL)
            {
                if((*cur1).val<(*cur2).val)
                {
                    p->next=cur1;
                    cur1=cur1->next;
                }
                else
                {
                    p->next=cur2;
                    cur2=cur2->next;
                }
                p=p->next;
            }
            if(cur1==NULL)
                p->next=cur2;
            else
                p->next=cur1;
        }
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值