合并两个排序链表

来源:互联网 发布:c语言苹果分级 编辑:程序博客网 时间:2024/05/03 21:02

1、问题描述

      将两个排序链表合并为一个新的排序链表。给出 1->3->8->11->15->null,2->null, 返回1->2->3->8->11->15->null。

2、实现思路

      若有一个链表为空,直接输出非空链表,若两个链表都非空,找出最小的那个data 作为新的链表的第一个元素,然后两个链表从头开始比较大小,依次放到新的链表。直到有一个链表结束,直接将另一个链表全部输出。

3、代码

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param ListNode l1 is the head of the linked list
     * @param ListNode l2 is the head of the linked list
     * @return: ListNode head of linked list
     */
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // write your code here
    ListNode *head=new ListNode;  
    ListNode *p=new ListNode;  
    if (l1==NULL)   return l2;  
    if (l2==NULL)   return l1;  
    if (l1->val< l2->val)
    {  
        head= l1;  
        l1 = l1->next;  
    }  
    else  
    {  
        head= l2;  
        l2 = l2->next;  
    }  
     p=head;
    while (l1 != NULL && l2 != NULL )  
    {  
        if (l1->val< l2->val)  
        {  
           p->next = l1;  
           p= l1;  
            l1 = l1->next;  
        }  
        else  
        {  
            p->next = l2;  
            p = l2;  
            l2 = l2->next;  
        }  
    }  
    if (l1==NULL)   p->next =l2;  
    if (l2==NULL)   p->next =l1; 
    head=p;
     return head;
    }
};

4、感想

     先从两个非空链表找到最小的元素作为新链表的第一个元素,再比较剩下的元素,依次放到新链表,排序后的元素要指向下一个,再继续比较大小,若有空链表直接返回剩下的非空链表。

0 0
原创粉丝点击