Merge k Sorted Lists

# Definition for singly-linked list.
class ListNode:
	def __init__(self, x):
		self.val = x
		self.next = None


class Solution:
    # @param {ListNode[]} lists
    # @return {ListNode}
    def mergeKLists(self, lists):
    	my_lists=[]
    	for x in xrange(len(lists)):
    		if lists[x]!=None:
    			my_lists.append(lists[x])
    	if len(my_lists)<=0:
    		return my_lists
    	if len(my_lists)==1:
    		return my_lists[0]
    	my_lists.sort(cmp=lambda x,y:cmp(x.val,y.val))
    	d=[]
    	l=my_lists[0]
    	for i in range(0,len(my_lists)-1,2):
    		l=self.merge2lists(my_lists[i],my_lists[i+1])
    		d.append(l)
    	if len(my_lists)%2==1:
    		d.append(my_lists[len(my_lists)-1])
    	return self.mergeKLists(d)

    def merge2lists(self,list_1,list_2):
    	if list_1==None:
    		return list_2
    	if list_2==None:
    		return list_1
    	head_1=head_2=None
    	if list_1.val>=list_2.val:
    		head_1=list_1     #big
    		head=head_2=list_2#small
    	else:
    		head_1=list_2
    		head=head_2=list_1
    	while head_2.next!=None:
    		if head_2.next.val>head_1.val:
    			head_2.next,head_1=head_1,head_2.next
    		head_2=head_2.next
    	if head_1!=next:
    		head_2.next=head_1
    	return head

你可能感兴趣的:(merge)