21. 合并两个有序链表/23. 合并K个排序链表

版权声明:只要梦想一天,只要梦想存在一天,就可以改变自己的处境。 https://blog.csdn.net/dongyanwen6036/article/details/85268826
1.合并两个有序链表
	 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {

		 ListNode* Phead = new ListNode(0);
		 ListNode* l3 = Phead;
		 while (l1&&l2)
		 {
			 if (l1->val<l2->val)
			 {
				 l3->next = l1;
				 l1 = l1->next;
			 }
			 else
			 {
				 l3->next = l2;
				 l2 = l2->next;
			 }
			 l3 = l3->next;
		 }
		 if (l1)l3->next = l1;
		 if (l2)l3->next = l2;
		 return Phead->next;
	 }  
2.合并K个排序链表

分析:采用分治法,最后两两合并。

c++ leetcode ac:

class Solution {
 public:
	 ListNode* mergeKLists(vector<ListNode*>& lists) {
		 int len = lists.size();
		 if (len == 0)return nullptr;
		 if (len == 1)return lists[0];
		 return Partion(lists,0,len-1);
	 }
	 ListNode* Partion(vector<ListNode*>& lists,int low,int high)
	 {
		 int mid = (low + high) / 2;
		 if (low == high)return lists[low];
		 if (low < high)
		 {
			 ListNode* left = Partion(lists, low, mid);
			 ListNode* right = Partion(lists,mid+1,high);
			 return mergeTwoLists(left, right);
		 }
		 return nullptr;
	 }
	 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {

		 ListNode* Phead = new ListNode(0);
		 ListNode* l3 = Phead;
		 while (l1&&l2)
		 {
			 if (l1->val<l2->val)
			 {
				 l3->next = l1;
				 l1 = l1->next;
			 }
			 else
			 {
				 l3->next = l2;
				 l2 = l2->next;
			 }
			 l3 = l3->next;
		 }
		 if (l1)l3->next = l1;
		 if (l2)l3->next = l2;
		 return Phead->next;
	 }  
 
	 
 };
			

猜你喜欢

转载自blog.csdn.net/dongyanwen6036/article/details/85268826