程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Merge two sorted linked lists

Merge two sorted linked lists

編輯:C++入門知識

題目:

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.


代碼如下:

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

        ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        if(l1==NULL)return l2;
        if(l2==NULL)return l1;
        ListNode *head1=NULL,*head2=NULL;
        if(l1->val<=l2->val)
        {
            head1=l1;
            head2=l2;
        }
        else
        {
            head1=l2;
            head2=l1;
        }
        ListNode *head=head1;
        while(head2!=NULL)
        {
            while(head1->next!=NULL&&head1->next->val<=head2->val)
            {
               head1=head1->next;
            }
            if(head1->next==NULL)
            {
                head1->next=head2;
                break;
            }
            else
            {
               ListNode *tmp=head2;
               head2=head2->next;
               tmp->next=head1->next;
               head1->next=tmp;
               head1=tmp;
            }
        }
        return head;
    }


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved