O(n)复杂度合并两个单调递链表

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

  • 算法思想:由于链表中没有使用空的头结点,算法复杂度稍微复杂一些,把思路想明白就可以。
    在这里插入图片描述

  • 演示算法

#include<iostream>
#include<stdlib.h>
using namespace std;
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};

void show(ListNode* point)
{
   while(point)
     {
        cout<<point->val;
        point=point->next;
     }
     cout<<endl;
}
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        ListNode* head1 = pHead1;
        ListNode* temp;
        ListNode* priev= NULL;    //先前的一个节点
        while(pHead2&&pHead1)
        {
            if(pHead2->val<=pHead1->val)
            {
               if(!priev)                      //需要调整头结点
               {
                  temp = pHead2->next;
                  pHead2->next = pHead1;
                  pHead1=pHead2;
                  pHead2=temp;
                  head1 = pHead1;   //标记新的节点
               }
               else                 //常规的插入方式
               {
                  temp=pHead2->next;
                  pHead2->next= priev->next;
                  priev->next=pHead2;
                  pHead2 = temp;

               }
            }
            else if(pHead2->val > pHead1->val)
             {
                priev = pHead1;
                pHead1 =pHead1->next;
        }
        }
        if(pHead2)   //链表二中还有元素
        {
           priev->next=pHead2;
        }
        return head1;
    }

int main()
{
    ListNode * list1=(ListNode*)malloc(sizeof(ListNode));
    ListNode * list2=(ListNode*)malloc(sizeof(ListNode));
    ListNode* head1 = list1;
    ListNode* head2 = list2;
    list2->val=0;
    list2->next=NULL;
    list1->val = 0;
    list1->next=NULL;
    for(int i = 1 ; i <5;i++)
    {
       ListNode* point = (ListNode*)malloc(sizeof(ListNode));
       point->val=i;
       point->next=NULL;
       list1->next=point;
       list1=point;
    }
    
    for(int i = 3 ; i <8;i++)
    {
       ListNode* point = (ListNode*)malloc(sizeof(ListNode));
       point->val=i;
       point->next=NULL;
       list2->next=point;
       list2=point;
    }
   ListNode*   head = Merge(head1,head2);
   show(head);

    return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Leader_wang/article/details/83217136