LeetCode 21. Merge Two Sorted Lists(链表题目)

LeetCode 21. 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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

思路分析

该题目比较简单,建立一个虚拟头结点,然后穿针引线(改变节点指针指向)即可,和归并排序中一样,注意判空,以及最后把退出循环没有遍历完的链表接上即可。

具体代码:

/**
 * 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==NULL)
            return l2;
        if(l2==NULL)
            return l1;
        //利用一个虚拟头结点,后边就是改变指针的指向就可以
        ListNode* dummy=new ListNode(0);
        ListNode* p=dummy;
        while(l1&&l2)
        {
            if(l1->val<l2->val)
            {
                p->next=l1;
                l1=l1->next;   
            }
            else
            {
                p->next=l2;
                l2=l2->next;
            }            
            p=p->next;
        }
        
        if(l1)
            p->next=l1;
        if(l2)
            p->next=l2;

        return dummy->next;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_20110551/article/details/81429074