<剑指Offer>面试题25: 合并两个排序的链表

题目描述 牛客网

  • 输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的

题目解读

  • 剑指Offer 145

代码

#include
using namespace std;

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};

class Solution {
public:

    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if(!pHead1){
            return pHead2;
        }
        else if(!pHead2){
            return pHead1;
        }

        ListNode *p = NULL;
        if(pHead1 -> val < pHead2 -> val){
            p = pHead1;
            p -> next = Merge(pHead1 -> next, pHead2);
        }
        else{
            p = pHead2;
            p -> next = Merge(pHead1, pHead2 -> next);
        }
        return p;
    }


    ListNode* create(int *array, int len){
        ListNode *p;
        ListNode *head = NULL;
        ListNode *tail = NULL;

        for(int i=0; i < len; i++){
            p = new ListNode(array[i]);

            if(!head){
                head = p;
            }
            else{
                tail -> next = p;
            }
            tail = p;
        }

        return head;
    }

    void print_Node(ListNode *head){
        while(head){
            cout<val<<" ";
            head = head->next;
        }
        cout<
<剑指Offer>面试题25: 合并两个排序的链表_第1张图片

总结展望

  • 递归的思想,要好好把握啊

你可能感兴趣的:(<剑指Offer>面试题25: 合并两个排序的链表)