《剑指offer》合并两个排序的链表

一、题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

二、输入描述

两个递增排序的链表

三、输出描述

合并成一个递增排序的链表

四、牛客网提供的框架

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {

    }
};

五、解题思路

从两个链表的链头开始,逐个比较两个链表现在所指的结点,小的进入新链表,并指针继续想想。直到其中的一个链表已经完成,把另外一个链表剩下的接到新的链表中去。

六、代码

(这代码好乱,有空再整理一下)

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        ListNode *head, *temp, *last;

        if(!pHead1) return pHead2;
        if(!pHead2) return pHead1;

        if(pHead1->val <= pHead2->val)
        {
            temp = pHead1;
            pHead1 = pHead1->next;
            head = temp;
            last = temp;
        }
        else
        {
            temp = pHead2;
            pHead2 = pHead2->next;
            head = temp;
            last = temp;
        }

        while(pHead1 && pHead2)
        {
            if(pHead1->val <= pHead2->val)
            {
                temp = pHead1;
                pHead1 = pHead1->next;
                last->next = temp;
                last = temp;
            }
            else
            {
                temp = pHead2;
                pHead2 = pHead2->next;
                last->next = temp;
                last = temp;
            }
        }

        if(pHead1) last->next = pHead1;
        if(pHead2) last->next = pHead2;

        return head;
    }
};
posted @ 2016-06-29 16:30  chenximcm  阅读(126)  评论(0编辑  收藏  举报