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

LeetCode之Merge k Sorted Lists

編輯:C++入門知識

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

多遍LeetCode之Merge Two Sorted Lists思想


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeKLists(vector &lists) {
        if (lists.size() == 0) return NULL;
		 while (lists.size()>1){
			 ListNode *mergelist = new ListNode(0);
			 ListNode *p = lists[0];
			 ListNode *q = lists[lists.size()-1];
			 lists.pop_back();
			 lists[0]=mergeTwoLists(p, q);
		 }
		 return lists[0];
    }
    
     ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
		 ListNode *list = new ListNode(0);
		 ListNode *p, *q, *r;
		 p = l1; q = l2; r = list;
		 while (p&&q){
			 if (p->val <= q->val){
				 r->next = p;
				 p = p->next;
			 }
			 else {
				 r->next = q;
				 q = q->next;
			 }
			 r = r->next;
		 }//while
		 r->next = q ? q : p;
		 return list->next;
	 }
};



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