검지offer 16: 두 개의 질서정연한 체인 테이블 병합

1263 단어
차례로 실현되다
#include 


using namespace std;

struct ListNode
{
public:
    int val;
    struct ListNode *next;
};

class Solution
{
public:

    


    // 16  
    // 

    ListNode* Merge(ListNode *pLeft, ListNode *pRight) {
        if (pLeft == NULL) {
            return pRight;

        }
        else if (pRight == NULL) {
            return pLeft;
        }

        ListNode *head = NULL;

        if (pLeft->val < pRight->val) {
            head = pLeft;
            head->next = Merge(pLeft->next, pRight);
        }
        else {
            head = pRight;
            head->next = Merge(pLeft, pRight->next);

            return head;
        }
    }




};



int main()
{
    



    ListNode list[4];
    list[0].val = 1;
    list[0].next = &list[1];

    list[1].val = 2;
    list[1].next = &list[2];

    list[2].val = 3;
    list[2].next = &list[3];
    list[3].val = 4;
    list[3].next = NULL;
    ListNode left;
    left.val = 5;
    left.next = NULL;

   

    Solution solu;


    ListNode *head = solu.Merge(&left,list);
    while (head != NULL) {
        cout << head->val << endl;
        head = head->next;
    }

    return 0;
}



좋은 웹페이지 즐겨찾기