LeetCode算法系列:21. Merge Two Sorted Lists

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/81946004

题目描述:


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) {
        ListNode* L = new ListNode(0);
        ListNode *P = L,*p1 = l1,*p2 = l2;
        while(p1 != NULL && p2 != NULL){
            if(p1->val < p2->val){
                P->next = p1;
                P = P->next;
                p1 = p1->next;
                
            }
            else if(p1->val >= p2->val){
                P->next = p2;
                P = P->next;
                p2 = p2->next;
            }
            else if(p1->val == p2->val){
                P->next = p1,P = P->next,p1 = p1->next;
                P->next = p2,P = P->next,p2 = p2->next;
              
            }
        }
        if(p1 == NULL)P->next = p2;
        else if(p2 == NULL)P->next = p1;
        return L->next;
    }
};

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/81946004
今日推荐