【面試準備】letcode—sort list

Sort a linked list in O(n log n) time using constant space complexity.


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* merged_list(ListNode* l_head,ListNode* r_head){
	ListNode* merged_head = NULL;
	ListNode* merged_tail = NULL;
	if(l_head == NULL){
		return r_head;
	}
	if(r_head == NULL){
		return l_head;
	}
	while(l_head != NULL && r_head != NULL){
		if(l_head->val <= r_head->val){
			if(merged_head == NULL){
				merged_head = l_head;
				merged_tail = l_head;
			}
			else{
				merged_tail->next = l_head;
				merged_tail = merged_tail->next;
			}
			l_head = l_head->next;
		}
		else{
			if(merged_head == NULL){
				merged_head = r_head;
				merged_tail = r_head;
			}
			else{
				merged_tail->next = r_head;
				merged_tail = merged_tail->next;
			}
			r_head = r_head->next;
		}
	}
	if(l_head != NULL){
		merged_tail->next = l_head;
	}
	else if(r_head != NULL){
		merged_tail->next = r_head;
	}
	return merged_head;
}

ListNode* sortList(ListNode* head){
	if(head == NULL || head->next == NULL){
		return head;
	}
	ListNode* node = head ;
	ListNode* slow = head ;
	ListNode* fast = head ; 
	while(fast->next != NULL && fast->next->next != NULL){
		slow = slow->next;
		fast = fast->next->next;
	}
	fast = slow->next;
	slow->next = NULL;
	slow = head;
	node = merged_list(sortList(slow),sortList(fast));
	return node;
}
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章